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

标签 python file

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

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

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/

相关文章:

c# - 目录监控

python - 在 Fedora 24 上的 Python3 中使用 `cairo.Region` 时出现段错误

python - Firestore (python) 监听器完成脚本而不是监听更改

c# - 从长路径自动创建目录

python - 如何将字符串写入远程机器上的文件?

python - 逐行处理内存中的文件并像python中的对象一样生成文件

python - AttributeError: 'tuple' 对象没有属性 'copy'

python - netcat 发送额外的 "X"UDP 数据包

python - 转换python espeak + subprocess代码直接播放输出音频

objective-c - 打开文件 - cocoa