给出的问题是我得到了一个包含一些文本的文件。我必须计算所有单词出现的次数。
到目前为止我尝试了什么:
def print_words(filename):
input_file = open(filename, 'r')
words = input_file.read().split()
result = {}
for word in words:
if word in result:
result.update({word:1})
else:
result[word] += 1
for count in result:
print(count + ' => ' + str(result[count]))
我得到的错误:
File "wordcount.py", line 50, in print_words
result[word] += 1
KeyError: 'We'
任何帮助将不胜感激。
最佳答案
当你重复你的话时:
for word in words:
if word in result:
result.update({word:1})
else:
result[word] += 1
您使用 update
将 word
添加到 result
仅当它已经存在时(如果 word结果:
)。如果它不存在,您无论如何都会尝试将它的值加一,而 Python 无法做到这一点,因此会出现 KeyError
。
最小的修复是:
- 交换
if
和else
block 内的行;或 - 更改为
if word not in result
。
或者,您可以使用 collections.defaultdict
进行简化:
from collections import defaultdict
result = defaultdict(int)
for word in words:
result[word] += 1
关于python - 为什么这个 Python 程序在更新字典时会引发错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23017288/