【发布时间】:2015-02-25 17:21:35
【问题描述】:
我的程序无法输出导入的 .txt 文件中单词出现的次数。对于我的作业,我只能使用字典功能(没有计数器),并且必须从文件中删除所有标点符号和大写字母。我们以古腾堡计划中的莎士比亚的哈姆雷特为例 (link)。我已经阅读了其他帖子,希望能纠正我的情况,但无济于事。这个由inspectorG4dget 编写的answer 似乎说明了我理想的程序代码,但是当我运行我的程序时,会为所选单词弹出一个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
这是一个所需的示例会话:
>>>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'
任何人都能够检测到我的代码有什么问题吗? 非常感谢任何帮助!
【问题讨论】:
-
在 HOPE 和 Shakespeak 模块中 word_dictionary 函数的实现是否相同?
-
是的,我暂时重命名了我的程序来测试代码。
-
1.从 if 语句中取出
wordDict[word] = wordDict.get(word, 0) + 1。 2.for line in filename.splitlines() -
@inspectorG4dget,如果我执行您的第一个建议,那不会阻止代码计算频率吗?如果我实施您的第二个建议,我是否必须删除第二个 .split() (在 line.strip() 之后)?
-
没有。由于您正在将整个文件内容读入
filename,因此for line in filename实际上会遍历每个字符,因为此时filename是一个字符串。您应该能够使用print(line)来验证这一点,作为健全性检查,以确保我做对了
标签: python python-3.x dictionary