我在csv文件中有三列,我想通过" title"列和计数特定单词的出现次数,所以我从编码开始,但我得到一个错误。代码是:
import csv
import collections
Title = collections.Counter()
with open('Green Occupations.csv') as input_file:
for row in csv.reader(input_file, delimiter=';'):
Title[row[1]] += 1
print 'Number of word "..": %s' % Tiltle['wind']
print Title.most_common()
我收到此错误:
Title[row[1]] += 1
IndexError: list index out of range
我拥有的数据的一个例子
+------------+---------------------------------+-------------------------+
| SOC Code | Title | Occupational Category |
+------------+---------------------------------+-------------------------+
| 11-1011.03 | Chief Sustainability Officers | New & Emerging |
| 11-1021.00 | General and Operations Managers | Enhanced Skills |
+------------+---------------------------------+-------------------------+
有什么想法吗? :)
答案 0 :(得分:0)
尝试以下代码
def get_count(title):
count=0
title=title.lower()
f=open('Green Occupations.csv')
l3=[[s.strip() for s in lines.split(',')] for lines in f.readlines()]
l4=[item[x] for item in l3]
for item in l4:
if item.split(' ')[0].strip('"').lower()==title:
count+=1
return count
print(get_count('Industrial'))
列x及以上列表中的如果第3列中的标题将x替换为3。
occurence=get_count(title=)
# will return no of occurence starting with title
答案 1 :(得分:0)
你能用熊猫吗? 这将使工作变得非常简单:
import pandas as pd
#Import data from csv
df = pd.read_csv(input_file, delimiter=';')
search_word = 'Officer' #example
# Check if each title contains the specified word and then count
counts = df['Title'].str.contains(search_word).sum()