[英]Python - List index out of range csv file
I am trying to make a dictionary that counts the number of each entry in the 13th to 17th column of a csv file. 我正在尝试制作一个字典,该字典计算csv文件第13至17列中每个条目的数量。 This is my code so far:
到目前为止,这是我的代码:
import unicodecsv
with open('hashtag.csv', 'r') as inp, open('hashtag3.csv', 'w') as out:
writer = unicodecsv.writer(out, delimiter=';', lineterminator='\n',encoding='ISO-8859-1')
stuff = unicodecsv.reader(inp, delimiter=';', encoding='ISO-8859-1')
my_dict={}
for row in stuff:
for i in range (13,18):
if row[i] in my_dict:
my_dict[row[i]]+=1
else:
my_dict[row[i]]=1
print my_dict
However, it tells me this, when I try to run it. 但是,当我尝试运行它时,它会告诉我这一点。
row[i] in my_dict: IndexError: list index out of range
my_dict中的row [i]:IndexError:列表索引超出范围
I tried taking each index on its own to figure out where it went wrong and found out, that it works with row[13], but not with any of the other integers in my range. 我尝试单独使用每个索引来找出错误的出处,并发现它适用于row [13],但不适用于我范围内的任何其他整数。 I thought maybe it's because in the other columns, there are some empty cells, but I can't even do an if-request in those other columns without getting the same error.
我认为可能是因为在其他列中有一些空单元格,但我什至不能在其他列中执行if-request而不出现相同的错误。
It seems like, for some reason, row
does not have all 13-18 columns. 出于某种原因,
row
似乎并没有全部13-18列。
Modify the for
loop to 将
for
循环修改for
for i in range(13,min(len(row),18)):
PS, PS,
Instead of the (somewhat) cumbersome if row[i] in my_dict
you might consider using defaultdict
: 您可以考虑使用
defaultdict
而不是麻烦的if row[i] in my_dict
from collections import defaultdict
my_dict = defaultdict(int) # accessing a new key returns zero
# ...
for row in stuff:
for i in xrange(13, min(18, len(row))):
my_dict[row[i]] += 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.