我首先使用Terminal/Python3
使用此方法。
>>>from collections import Counter
>>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>>> Counter(z)
Counter({'blue': 3, 'red': 2, 'yellow': 1})
但是我意识到我有超过800个元素,所以想以某种方式打开txt文件,然后继续这个措施。
答案 0 :(得分:0)
您只需将文本文件拆分为一个非常简单的列表。示例代码如下所示:
from collections import Counter
f = open("test.txt") # open file (replace "test" with file name)
z = f.read().split() # read and split into list (default splits by spaces)
f.close() # close file
print Counter(z) # add parenthesis if python 3
答案 1 :(得分:0)
只需传入文件处理程序:
from collections import Counter
with open('large-file.txt') as f:
c = Counter(f)
print(c.most_common())