Python计数字词而非字母
我正在尝试创建一个程序,读取一个文本文件,并计算里面有多少个不同的单词。 我已经完成了大部分工作,但现在遇到了一个问题,就是计数器现在只在计算字母,而不是单词。
import collections
with open ("file.txt" ,"r") as myfile:
data=myfile.read()
[i.split(" ") for i in data]
x=collections.Counter(data)
print (x)
我的目标是通过空格来分割列表,这样每个单词就会成为列表中的一个对象。但是这个方法没有成功。
结果:
Counter({' ': 1062, 'e': 678, 't': 544, 'o': 448, 'n': 435, 'a': 405, 'i': 401, 'r': 398, 's': 329, 'c': 268, 'm': 230, 'h': 216, 'u': 212, 'd': 190, 'l': 161, 'p': 148, 'f': 107, 'g': 75, 'y': 68, '\n': 65, ',': 61, 'b': 55, 'w': 55, 'v': 55, '.': 53, 'N': 32, 'A': 20, 'T': 19, '"': 18, ')': 17, '(': 17, 'C': 17, 'k': 16, "'": 16, 'I': 16, 'x': 15, '-': 14, 'E': 13, 'q': 12, 'V': 10, 'U': 9, ';': 7, '1': 6, 'j': 5, '4': 5, 'P': 5, 'D': 5, '9': 5, 'L': 4, 'z': 4, 'W': 4, 'O': 3, 'F': 3, '5': 3, 'J': 2, '3': 2, 'S': 2, 'R': 2, '0': 1, ':': 1, 'H': 1, '2': 1, '/': 1, 'B': 1, 'M': 1, '7': 1})
2 个回答
0
为了回答这个问题,不是用一个字符串来更新计数器,而是用一个包含一个或多个字符串的列表。
然后,如果你的代码是:
from collections import Counter
words_count = Counter("tiger")
记住,字符串其实是一个字符的列表。代码就像是:
from collections import Counter
words_count = Counter("t", "i", "g", "e", "r")
否则,如果你的代码是:
from collections import Counter
words_count = Counter(["tiger"])
那么,列表中的每个元素就是一个完整的单词。
2
你的列表推导式没有被赋值,所以它实际上没有任何作用。
把分割后的文本传给 collections.Counter()
:
x = collections.Counter(data.split())
我使用了 str.split()
而没有传入参数,这样可以确保你在任意宽度的空白字符上进行分割,同时在分割时也能包含换行符;比如你的 Counter()
里面有65个换行符,这些其实是多余的。
在上下文中,稍微简洁一些:
from collections import Counter
with open ("file.txt") as myfile:
x = Counter(myfile.read().split())
print(x)