我正在尝试编写一个过滤器,在其中尝试查找键和值频率计数。在尝试其中一个代码块时,我面临以下错误困难。
数据是关于 Twitter 用户和相应的关键字。我正在尝试获取用户推文计数的频率以及各个用户发布的每个唯一关键字的计数。该数据集大约有 1000 行,而我在输入中只显示了其中的 20 行。
输入
tweetcricscore 7.15E+17 3/30/2016 #wt20
tweetcricscore 7.15E+17 3/30/2016 #sausvsvic
tweetcricscore 7.15E+17 3/30/2016 #wt20
tweetcricscore 7.15E+17 3/30/2016 #sausvsvic
tweetcricscore 7.14E+17 3/28/2016 #wt20
tweetcricscore 7.14E+17 3/28/2016 #sausvsvic
tweetcricscore 7.14E+17 3/27/2016 #wt20
tweetcricscore 7.14E+17 3/27/2016 #sausvsvic
tweetcricscore 7.14E+17 3/27/2016 #wt20
tweetcricscore 7.14E+17 3/27/2016 #sausvsvic
tweetcricscore 7.14E+17 3/26/2016 #wt20
tweetcricscore 7.14E+17 3/26/2016 #canvsnk
tweetcricscore 7.14E+17 3/26/2016 #wt20
tweetcricscore 7.14E+17 3/26/2016 #sausvsvic
tweetcricscore 7.14E+17 3/26/2016 #wt20
tweetcricscore 7.14E+17 3/26/2016 #sausvsvic
tweetcricscore 7.14E+17 3/26/2016 #wt20
tweetcricscore 7.14E+17 3/26/2016 #sausvsvic
tweetcricscore 7.13E+17 3/23/2016 #wt20
tweetcricscore 7.13E+17 3/23/2016 #indvsban
代码:
with open('filter_1.csv', 'rb') as inp,open('filter_2.csv', 'wb') as out:
writer = csv.writer(out)
'''for row in csv.reader(inp):
l.append(row[0])'''
for row in csv.reader(inp):
try:
key_val = row[0],row[3]
d[key_val] +=1
except Exception as e:
pass
od = collections.OrderedDict(sorted(d.items()))
for key,values in od.iteritems():
writer.writerow([key[0],l.count(key[0]),key[3],values])
预期输出
tweetcricscore 234 #afgvssco 51
tweetcricscore 234 #afgvszim 46
tweetcricscore 234 #banvsire 12
tweetcricscore 234 #banvsned 46
tweetcricscore 234 #canvsnk 1
tweetcricscore 234 #cricket 178
tweetcricscore 234 #engvswi 46
tweetcricscore 234 #hkvssco 23
tweetcricscore 234 #indvsban 1
tweetcricscore 234 #sausvsvic 8
tweetcricscore 234 #wt20 56
我收到以下错误
28
29 for key,values in od.iteritems():
---> 30 writer.writerow([key[0],l.count(key[0]),key[3],values])
32
IndexError: tuple index out of range
该代码只是处理程序的一部分,这部分向我显示了过滤输入时的错误。 任何建议表示赞赏。提前致谢
最佳答案
我无法运行您提供的示例,但根据阅读代码,您似乎正在生成一个 dict
,其中键是每个都有两个元素的元组:
key_val = row[0],row[3]
d[key_val] +=1
然后生成 OrderedDict
,其中使用相同的键并迭代其上的项目:
for key,values in od.iteritems():
writer.writerow([key[0],l.count(key[0]),key[3],values])
在第二行,您尝试从 key
获取索引 3 处的元素,这自然会失败,因为它只有两个元素。如果您将 key[3]
更改为 key[1]
,它应该按预期工作。
关于python - Key_Value 计数过滤字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37053507/