gpt4 book ai didi

python - 为什么这个 Python 程序在更新字典时会引发错误?

转载 作者:行者123 更新时间:2023-11-28 21:20:14 26 4
gpt4 key购买 nike

给出的问题是我得到了一个包含一些文本的文件。我必须计算所有单词出现的次数。

到目前为止我尝试了什么:

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

您使用 updateword 添加到 result 仅当它已经存在时(如果 word结果:)。如果它不存在,您无论如何都会尝试将它的值加一,而 Python 无法做到这一点,因此会出现 KeyError

最小的修复是:

  1. 交换 ifelse block 内的行;或
  2. 更改为 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com