【问题标题】:How can I find frequency of a specific word from document in python?如何从 python 文档中找到特定单词的频率?
【发布时间】:2015-12-31 00:48:26
【问题描述】:

我想从文本文件中找出特定单词的频率。假设在我的文档中我有一行“这是我是”如果我输入“是”输出应该是 3 如果我的输入是“我”输出应该是 1。我正在尝试这段代码

    import re
    doc1 = re.findall(r'\w+', open('E:\doc1.txt').read().lower())
    words = raw_input("Input Number :: ")
    docmtfrequency1 =  words.count(words)

但它没有提供所需的输出

【问题讨论】:

  • 应该是doc1.count(words)
  • words.count(words) 应该做什么?

标签: python-2.7 count file-handling vsm


【解决方案1】:
如果我了解您的问题,

collections.Counter() 已涵盖此内容。 文档中的示例似乎与您的问题相符。

# Tally occurrences of words in a list
cnt = Counter()
for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
    cnt[word] += 1
print cnt


# Find the ten most common words in Hamlet
import re
words = re.findall('\w+', open('hamlet.txt').read().lower())
Counter(words).most_common(10)

从上面的例子你应该可以做到:

import re
import collections
words = re.findall('\w+', open('1976.03.txt').read().lower())
print collections.Counter(words)

展示一种方式的幼稚方法。

wanted = "fish chips steak"
cnt = Counter()
words = re.findall('\w+', open('1976.03.txt').read().lower())
for word in words:
    if word in wanted:
        cnt[word] += 1
print cnt

【讨论】:

    猜你喜欢
    • 2020-10-28
    • 2019-09-01
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 2011-07-21
    • 2020-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多