合并和汇总类似的CSV条目

2024-09-19 20:38:24 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我的CSV文件如下:

  • 爱,大概200
  • 爱,就像,50岁
  • 说吧,索赔,30

其中数字代表在不同语境中同时出现的单词的计数。在

我想把相似的词的计数合并起来。所以我想输出如下内容:

  • 爱,像,250
  • 说吧,索赔,30

我一直在四处寻找,但似乎我被这个简单的问题所困扰。在


Tags: 文件csv内容代表数字单词计数语境
2条回答

没有看到一个确切的CSV很难知道什么是合适的。下面的代码假设最后一个标记是count,并且它匹配最后一个逗号之前的所有内容。在

# 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]

并输出:

^{pr2}$

根据你的申请是什么,我想我会建议你在这里使用一个计数器。Counter是一个python集合模块,它允许您跟踪所有东西的数量。例如,在您的情况下,您可以迭代地更新counter对象。在

例如:

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,也可以继续使用它。在

相关问题 更多 >