我正在尝试使用python计算文本文件中的单词频率。
我使用以下代码:
openfile=open("total data", "r")
linecount=0
for line in openfile:
if line.strip():
linecount+=1
count={}
while linecount>0:
line=openfile.readline().split()
for word in line:
if word in count:
count[word]+=1
else:
count[word]=1
linecount-=1
print count
但我得到一本空字典。 “print count”给出{}作为输出
我也尝试过使用:
from collections import defaultdict
.
.
count=defaultdict(int)
.
.
if word in count:
count[word]=count.get(word,0)+1
但我又得到了一本空字典。我不明白我做错了什么。有人可以指出吗?
答案 0 :(得分:9)
此循环for line in openfile:
将文件指针移动到文件末尾。
因此,如果您想再次读取数据,请将指针(openfile.seek(0)
)移动到文件的开头或重新打开文件。
要更好地使用Collections.Counter
from collections import Counter
with open("total data", "r") as openfile:
c = Counter()
for line in openfile:
words = line.split()
c.update(words)
答案 1 :(得分:1)
初始化openfile.seek(0)
后立即添加count
。那会把读指针放到文件的开头
答案 2 :(得分:1)
这是计算文件中单词频率的一种更直接的方法:
from collections import Counter
def count_words_in_file(file_path):
with open(file_path) as f:
return Counter(f.read().split())
示例:
>>> count_words_in_file('C:/Python27/README.txt').most_common(10)
[('the', 395), ('to', 202), ('and', 129), ('is', 120), ('you', 111), ('a', 107), ('of', 102), ('in', 90), ('for', 84), ('Python', 69)]