gpt4 book ai didi

python - 合并并求和相似的 CSV 条目

转载 作者:行者123 更新时间:2023-12-01 05:37:01 24 4
gpt4 key购买 nike

假设我的 CSV 文件如下:

  • 喜欢,200
  • 喜欢,50
  • 说,声称,30

其中数字代表在不同上下文中同时出现的单词的计数。

我想合并相似单词的计数。所以我想输出类似的内容:

  • 喜欢,250
  • 说,声称,30

我一直在环顾四周,但似乎我陷入了这个简单的问题。

最佳答案

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

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

并输出:

say, claim :  30
love : 20
love, like : 250

关于python - 合并并求和相似的 CSV 条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18690224/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com