如何读取.txt文件并计算相同的元素并用Python列出它们?

时间:2016-05-04 03:20:50

标签: python counter

我首先使用Terminal/Python3使用此方法。

>>>from collections import Counter
>>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>>> Counter(z)
Counter({'blue': 3, 'red': 2, 'yellow': 1})

但是我意识到我有超过800个元素,所以想以某种方式打开txt文件,然后继续这个措施。

2 个答案:

答案 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())