python - 仅使用字典 Python 3 计算 .txt 文件中的词频

标签 python python-3.x dictionary

我一直无法让程序输出某个单词在导入的 .txt 文件中出现的次数。对于我的作业,我只能使用字典功能(无计数器),并且必须从文件中删除所有标点符号和大写字母。我们使用古腾堡计划中的莎士比亚的哈姆雷特作为示例 ( link )。我读过其他帖子,希望能解决我的情况,但无济于事。这个answer作者:inspectorG4dget 似乎说明了我理想的程序代码,但是当我运行我的程序时,会针对所选单词弹出一个 KeyError 。这是我编辑的程序(仍然收到带有此代码的错误消息):

def word_dictionary(x):
    wordDict = {}
    filename = open(x, "r").read()
    filename = filename.lower()
    for ch in '"''!@#$%^&*()-_=+,<.>/?;:[{]}~`\|':
        filename = filename.replace(ch, " ")
    for line in filename:
        for word in line.strip().split():
            if word not in wordDict:
                wordDict[word] = wordDict.get(word, 0) + 1
    return wordDict

这是一个所需的示例 session :

>>>import shakespeare
>>>words_with_counts = shakespeare.word_dictionary("/Users/username/Desktop/hamlet.txt")
>>>words_with_counts[’the’]
993
>>>words_with_counts[’laugh’]
6

这就是我得到的:

>>> import HOPE
>>> words_with_counts = HOPE.word_dictionary("hamlet.txt")
>>> words_with_counts["the"]
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    words_with_counts["the"]
KeyError: 'the'

有人能够检测出我的代码有什么问题吗? 非常感谢任何帮助!

最佳答案

您的字典使用了错误的键。循环应如下所示:

for word in filename.strip().split():
    if word not in wordDict:
        wordDict[word] = 0
    wordDict[word] += 1

关于python - 仅使用字典 Python 3 计算 .txt 文件中的词频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28725503/

相关文章:

python - 使用 Python strptime 将日期字符串列表转换为日期时间非常慢

python - 带有 jinja 的条件元素类,如果列表项包含某个项目,我希望 div 获得一个类

python - 如何在QWebEnginePage-pyqt5中使用POST方法打开URL

python - iter,值,字典中的项目不起作用

.net - 为什么 .NET 字典发牢骚?

python - 我可以忽略 setuptools MANIFEST.in 中的符号链接(symbolic link)吗?

Python/C++ 绑定(bind),如何将静态 C++ 库 (portaudio) 与 distutils 链接起来?

python - 将 int 拆分为字节的快速方法

python - 由于 python 将主机读取为元组,尝试进行套接字时出现类型错误

python - 用于存储游戏 map 的列表或字典