【问题标题】:python, how to count most common words in text filepython,如何计算文本文件中最常用的单词
【发布时间】:2017-03-12 15:41:48
【问题描述】:

我对 Python 很陌生,但我需要创建一个程序来计算两个文本文件中最常见的单词,然后打印这些单词出现的频率,按最常见的顺序排列。到目前为止,我有以下代码,如您所见,我非常迷茫!

import re
import collections

with open('Bible txt.txt') as f:
text = f.read()

words = re.compile(r"a-zA-Z'").findall(text)
counts = collections.Counter(words)

没有错误,但是当我运行它时出现“进程完成,错误代码 = 0”

我知道还有其他类似的问题,但我尝试过的其他方法似乎都不起作用。我为此使用 PyCharm CE。

任何帮助将不胜感激

【问题讨论】:

  • 你不输出任何东西,例如将 10 个最常用的单词打印到标准输出:print(counts.most_common(10))
  • 你是如何运行它的?该输出可能只是意味着该过程没有错误地完成。

标签: python count frequency


【解决方案1】:
from collections import Counter

with open('Bible txt.txt') as fin:
    counter = Counter(fin.read().strip().split())

print(counter.most_common())

【讨论】:

    猜你喜欢
    • 2014-08-11
    • 2017-04-24
    • 2014-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多