如何从 python 中的文档中找到特定单词的频率?
How can I find frequency of a specific word from document in python?
我想从文本文件中找出特定单词的频率。假设在我的文档中我有一行 "this is me is is " 如果我输入 'is' 输出应该是 3 如果我的输入是 'me' 输出应该是 1. 我正在尝试这个代码
import re
doc1 = re.findall(r'\w+', open('E:\doc1.txt').read().lower())
words = raw_input("Input Number :: ")
docmtfrequency1 = words.count(words)
但它没有给出所需的输出
如果我了解您的问题,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
我想从文本文件中找出特定单词的频率。假设在我的文档中我有一行 "this is me is is " 如果我输入 'is' 输出应该是 3 如果我的输入是 'me' 输出应该是 1. 我正在尝试这个代码
import re
doc1 = re.findall(r'\w+', open('E:\doc1.txt').read().lower())
words = raw_input("Input Number :: ")
docmtfrequency1 = words.count(words)
但它没有给出所需的输出
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