我一直无法让程序输出某个单词在导入的 .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/