Python 从csv词频列表中删除重复项
目前我被这个词频表难住了。我几乎得到了我的最终结果,那就是打印每个单词及其计数,但我似乎无法摆脱重复的内容。如果有人能帮我完成最后一部分,我将不胜感激 这就是我目前所拥有的Python 从csv词频列表中删除重复项,python,python-3.x,Python,Python 3.x,目前我被这个词频表难住了。我几乎得到了我的最终结果,那就是打印每个单词及其计数,但我似乎无法摆脱重复的内容。如果有人能帮我完成最后一部分,我将不胜感激 这就是我目前所拥有的 import csv input_file = input() ##contents of input_file are -- hello,cat,man,hey,dog,boy,Hello,man,cat,woman,dog,Cat,hey,boy with open(input_file, 'r') as csvfi
import csv
input_file = input()
##contents of input_file are -- hello,cat,man,hey,dog,boy,Hello,man,cat,woman,dog,Cat,hey,boy
with open(input_file, 'r') as csvfile:
csvfile = csv.reader(csvfile)
count = 0
for line in csvfile:
for word in line:
count = line.count(word)
##I am trying to print the words and count without any duplicates
print(word, count)
您可以使用
字典
,因为它不允许重复键。看一看
with open(input_file, 'r') as csvfile:
csvfile = csv.reader(csvfile)
my_words = dict()
for line in csvfile:
for word in line:
try:
# If it's duplicated, add one
my_words[word] += 1
except KeyError:
# If it's the first occurrence, set as one
my_words[word] = 1
for word, count in my_words.items():
print(word, count)
是的,它们之间只有逗号。非常感谢!