# You'd need to replace the below with the appropriate code to open your file
file = """love, like, 200
love, like, 50
love, 20
say, claim, 30"""
file = file.split("\n")
words = {}
for line in file:
word,count=line.rsplit(",",1) # Note this uses String.rsplit() NOT String.split()
words[word] = words.get(word,0) + int(count)
for word in words:
print word,": ",words[word]
from collections import Counter
with open("your_file.txt", "rb") as source:
counter = Counter()
for line in source:
entry, count = line.rsplit(",", 1)
counter[entry] += int(count)
没有看到一个确切的CSV很难知道什么是合适的。下面的代码假设最后一个标记是count,并且它匹配最后一个逗号之前的所有内容。在
并输出:
^{pr2}$根据你的申请是什么,我想我会建议你在这里使用一个计数器。Counter是一个python集合模块,它允许您跟踪所有东西的数量。例如,在您的情况下,您可以迭代地更新counter对象。在
例如:
此时,您可以将数据写回csv,也可以继续使用它。在
相关问题 更多 >
编程相关推荐