【问题标题】:Counting specific 3-word-phrases in file using Python 3使用 Python 3 计算文件中特定的 3 词短语
【发布时间】:2018-06-25 00:47:30
【问题描述】:

我尝试使用以下代码在 txt 文件中查找和计算特定的三词短语:

phrases = ['hi there you','eat sausage bread', ...]

with open('test.txt') as f:
    for word in phrases:
        contents = f.read()
        count = contents.count('word')
        print(word, count)

Python 列出了我的每一个短语,但它并没有准确计算。相反,第一个短语始终是 63,以下任何一个都是 0。因为我有 100 多个短语以及许多不同的文件,所以单独计算任何短语是浪费时间(顺便说一句,它适用于这个脚本) .也许有人可以清除我明显的错误或知道可能的解决方案,我将非常感激。

【问题讨论】:

  • 什么是pro2?而且你的缩进似乎也消失了......
  • 你能显示一些你的文本文件吗?
  • “pro2”应该是“短语”

标签: python python-3.x word-count


【解决方案1】:

您将每个单词的整个文件读入contents。由于您永远不会将文件指针恢复到文件的开头,因此在第一个 read 之后它只存储一个空字符串。

通过仅读取文件一次来修复。

with open('test.txt') as f:
    contents = f.read()
    for word in phrases:
        count = contents.count(word)
        print(word, count)

【讨论】:

  • 不应该是count = contents.count(word)吗?
  • @MaxPower:如果某个特定答案对您有所帮助,我们鼓励您发送电子邮件至accept it,以便其他观众看到您的问题有适合您的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-12
  • 1970-01-01
相关资源
最近更新 更多