所以,我有文本文件(段落),我需要读取文件并创建一个包含文件中每个不同单词的字典作为键,每个键的相应值将是一个整数,显示频率文本文件中的单词。 字典应该是什么样子的一个例子:
{'and':2, 'all':1, 'be':1, 'is':3}
等
def create_word_frequency_dictionary () :
filename = 'dictionary.txt'
infile = open(filename, 'r')
line = infile.readline()
my_dictionary = {}
frequency = 0
while line != '' :
row = line.lower()
word_list = row.split()
print(word_list)
print (word_list[0])
words = word_list[0]
my_dictionary[words] = frequency+1
line = infile.readline()
infile.close()
print (my_dictionary)
create_word_frequency_dictionary()
任何帮助将不胜感激。
答案 0 :(得分:3)
文档将collections
模块定义为“高性能容器数据类型”。考虑使用collections.Counter
而不是重新发明轮子。
from collections import Counter
filename = 'dictionary.txt'
infile = open(filename, 'r')
text = str(infile.read())
print(Counter(text.split()))
<强>更新强> 好的,我修复了你的代码,现在它可以工作,但Counter仍然是一个更好的选择:
def create_word_frequency_dictionary () :
filename = 'dictionary.txt'
infile = open(filename, 'r')
lines = infile.readlines()
my_dictionary = {}
for line in lines:
row = str(line.lower())
for word in row.split():
if word in my_dictionary:
my_dictionary[word] = my_dictionary[word] + 1
else:
my_dictionary[word] = 1
infile.close()
print (my_dictionary)
create_word_frequency_dictionary()
答案 1 :(得分:1)
如果你没有使用具有Counter的python版本:
>>> import collections
>>> words = ["a", "b", "a", "c"]
>>> word_frequency = collections.defaultdict(int)
>>> for w in words:
... word_frequency[w] += 1
...
>>> print word_frequency
defaultdict(<type 'int'>, {'a': 2, 'c': 1, 'b': 1})
答案 2 :(得分:0)
只需将my_dictionary[words] = frequency+1
替换为my_dictionary[words] = my_dictionary[words]+1
。