我想使用字典来统计文件中每个单词的出现(文件中所有单词均为小写字母,并且文件中不包含标点符号)。
我想优化代码,因为我知道列表会花费不必要的时间。
def create_dictionary(filename):
d = {}
flat_list = []
with open(filename,"r") as fin:
for line in fin:
for word in line.split():
flat_list.append(word)
for i in flat_list:
if d.get(i,0) == 0:
d[i] = 1
else :
d[i] +=1
return d
例如,包含的文件:
i go to the market to buy some things to
eat and drink because i want
to eat and drink
应返回:
{'i': 2, 'go': 1, 'to': 4, 'the': 1, 'market': 1, 'buy': 1, 'some': 1, 'things': 1, 'eat': 2, 'and': 2, 'drink': 2, 'because': 1, 'want': 1}
我可以改善什么?
答案 0 :(得分:1)
只需使用collections.Counter
:
with open(filename,"r") as fin:
print(Counter(fin.read().split()))