我正在尝试加快我的项目来计算词频。我有 360 多个文本文件,我需要获取单词总数以及另一个单词列表中每个单词出现的次数。我知道如何使用单个文本文件来做到这一点。
>>> import nltk
>>> import os
>>> os.chdir("C:\Users\Cameron\Desktop\PDF-to-txt")
>>> filename="1976.03.txt"
>>> textfile=open(filename,"r")
>>> inputString=textfile.read()
>>> word_list=re.split('\s+',file(filename).read().lower())
>>> print 'Words in text:', len(word_list)
#spits out number of words in the textfile
>>> word_list.count('inflation')
#spits out number of times 'inflation' occurs in the textfile
>>>word_list.count('jobs')
>>>word_list.count('output')
获取“通货膨胀”、“就业”、“产出”个人的频率太乏味了。我可以把这些单词放到一个列表中,同时找出列表中所有单词的出现频率吗?基本上this https://stackoverflow.com/questions/4520876/counting-the-frequency-of-specific-words-in-text-file使用Python。
示例:而不是这个:
>>> word_list.count('inflation')
3
>>> word_list.count('jobs')
5
>>> word_list.count('output')
1
我想这样做(我知道这不是真正的代码,这就是我寻求帮助的内容):
>>> list1='inflation', 'jobs', 'output'
>>>word_list.count(list1)
'inflation', 'jobs', 'output'
3, 5, 1
我的单词列表将包含 10-20 个术语,因此我需要能够将 Python 指向单词列表以获取其计数。如果输出能够复制+粘贴到 Excel 电子表格中,其中单词作为列,频率作为行,那就太好了
Example:
inflation, jobs, output
3, 5, 1
最后,任何人都可以帮助自动化所有文本文件吗?我想我只需将 Python 指向该文件夹,它就可以从新列表中为 360 多个文本文件中的每一个执行上述字数统计。看起来很容易,但我有点卡住了。有什么帮助吗?
像这样的输出会很棒:
文件名1
通货膨胀、就业、产出
3, 5, 1
Filename2
inflation, jobs, output
7, 2, 4
Filename3
inflation, jobs, output
9, 3, 5
Thanks!