gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:45:20 25 4
gpt4 key购买 nike

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

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