【问题标题】:Count word frequency in a .txt file using only dictionary Python 3仅使用字典 Python 3 计算 .txt 文件中的词频
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 我已经更正了那部分代码,但仍然收到相同的错误消息。也许这是我对函数的调用??
  • @Emily 我刚刚又看了一遍,并已将我的循环编辑为正确。另一个问题是.read() 将整个文件读入一个字符串。然后使用for line in filename 循环该字符串。这不会将其拆分为行,而是将其拆分为单个字符。删除该循环后,一切正常。但是,我得到了 the 这个词的 1109 个计数(不是 993 个)。
【解决方案2】:
if word not in wordDict

`wordDict[1]` -> `wordDict[word]`

(两次出现)

你为什么要计算长度?

【讨论】:

  • 天哪,这是我没有发现的疏忽。谢谢!
  • 更简洁,wordDict[word] = wordDict.get(word, 0) + 1 或使用setdefault
【解决方案3】:

我认为错误是因为

for line in filename:

这里的'filename'是一个字符串,不是文件的输入

filename = open(x, "r").read()

被使用了。 “线”是拉出每个字符,而不是线。尝试用下面的函数替换代码

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

【讨论】:

    猜你喜欢
    • 2021-11-15
    • 1970-01-01
    • 2019-05-05
    • 2015-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 2018-06-25
    相关资源
    最近更新 更多