如何计算文档中的单词数
我想知道在一个文档中数单词的最好方法是什么。如果我有自己的“corp.txt”文本文件,并且想知道“students, trust, ayre”这几个词在这个文件中出现的频率,我可以用什么方法呢?
是不是可以用下面的其中一种:
....
full=nltk.Text(mycorpus.words('FullReport.txt'))
>>> fdist= FreqDist(full)
>>> fdist
<FreqDist with 34133 outcomes>
// HOW WOULD I CALCULATE HOW FREQUENTLY THE WORDS
"students, trust, ayre" occur in full.
谢谢,
Ray
4 个回答
4
你快到了!你可以用你感兴趣的单词来查找频率分布。试试下面这个:
print fdist['students']
print fdist['ayre']
print fdist['full']
这样你就能得到每个单词出现的次数。你提到“频率”——频率和出现次数是不同的,频率可以这样计算:
print fdist.freq('students')
print fdist.freq('ayre')
print fdist.freq('full')
4
大多数人会使用一个叫做默认字典(defaultdictionary)的东西,里面的默认值设为0。每当你看到一个单词的时候,就把这个单词对应的值加一:
total = 0
count = defaultdict(lambda: 0)
for word in words:
total += 1
count[word] += 1
# Now you can just determine the frequency by dividing each count by total
for word, ct in count.items():
print('Frequency of %s: %f%%' % (word, 100.0 * float(ct) / float(total)))
12
我建议你看看 collections.Counter 这个工具。特别是当你处理大量文本时,它非常有效,唯一的限制就是你的电脑内存有多少。比如说,它在一台有12GB内存的电脑上,花了一天半的时间就统计了300亿个词。下面是个伪代码(变量 Words 实际上会指向一个文件或类似的东西):
from collections import Counter
my_counter = Counter()
for word in Words:
my_counter.update(word)
完成后,所有的词都会存储在一个叫 my_counter 的字典里,然后你可以把它写入硬盘或者存储到其他地方(比如 sqlite)。