如何编写一个只统计csv列表中不同单词的列表?
输入:input1.csvinput1.csv = hello,cat,man,hey,dog,boy, hello, man,cat,woman,dog, cat, hey,boy
预期输出:
hello 1
猫2
男人2
狗2
男孩2
你好1
女人1
猫1
import collections
with open(fname,"r") as f:
word_counter = collections.Counter(f.read().split(","))
print(word_counter.most_common())
这可能是我要做的…
首先,输入的文件可以而且确实不同,因此input()
对于不同的文件名很重要。其次,我们必须做一个独特的列表,这样我们就有东西可以使用,建立unique = []
是很重要的,把你的列表放在某个地方。最后,这个场景需要两个循环。这可以以不同的方式构建,但我发现这种方式是最容易编写和理解的代码。
import csv
unique_list = []
with open(input(), 'r') as csvfile:
csv_reader = csv.reader(csvfile, delimiter=',')
for row in csv_reader:
for word in row:
if word not in unique_list:
unique_list.append(word)
for unique_word in unique_list:
count = row.count(unique_word)
print(unique_word, count)