Python - 在文本文件中查找单词列表的单词频率

问题描述:

我正在加速我的项目来计算单词频率。我有360多个文本文件,我需要获取单词总数以及出现另一个单词列表中的每个单词的次数。我知道如何用单个文本文件来做到这一点。Python - 在文本文件中查找单词列表的单词频率

>>> 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') 

太繁琐得到'通货膨胀','工作','输出'个人的频率。我可以将这些单词放入列表中,并同时查找列表中所有单词的频率吗?与Python基本上this

例:取而代之的是:

>>> 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电子表格的话为列,频率为行

例子:

inflation, jobs, output 
3, 5, 1 

最后,任何人都可以帮助自动化这个所有的文字文件?我想我只是指向Python文件夹,它可以从每个360 +文本文件的新列表中进行上述单词计数。看起来很简单,但我有点卡住了。任何帮助?

像这样的输出将是非常美妙: FILENAME1 通货膨胀,就业,产出 3,5,1

Filename2 
inflation, jobs, output 
7, 2, 4 

Filename3 
inflation, jobs, output 
9, 3, 5 

谢谢!

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 
+0

我一直在柜台现在愚弄了几个小时,仍然无法得到它。 – CoS 2013-02-17 13:18:24

+0

上面的例子会给我讲解我的文本文件中所有独特的单词(在我的例子中超过3000个独特的单词)。我只需要文本文件中10-20个特定单词的计数。 – CoS 2013-02-17 13:21:32

+0

我认为这将为清单工作,非常感谢你!我盯着那个柜台页面好几个小时哈哈 – CoS 2013-02-17 13:30:05

一个可能实现(使用计数器)...

而不是打印输出的,我认为这将是简单的写入csv文件,并导入到Excel中。查看http://docs.python.org/2/library/csv.html并替换print_summary

import os 
from collections import Counter 
import glob 

def word_frequency(fileobj, words): 
    """Build a Counter of specified words in fileobj""" 
    # initialise the counter to 0 for each word 
    ct = Counter(dict((w, 0) for w in words)) 
    file_words = (word for line in fileobj for word in line.split()) 
    filtered_words = (word for word in file_words if word in words) 
    return Counter(filtered_words) 


def count_words_in_dir(dirpath, words, action=None): 
    """For each .txt file in a dir, count the specified words""" 
    for filepath in glob.iglob(os.path.join(dirpath, '*.txt')): 
     with open(filepath) as f: 
      ct = word_frequency(f, words) 
      if action: 
       action(filepath, ct) 


def print_summary(filepath, ct): 
    words = sorted(ct.keys()) 
    counts = [str(ct[k]) for k in words] 
    print('{0}\n{1}\n{2}\n\n'.format(
     filepath, 
     ', '.join(words), 
     ', '.join(counts))) 


words = set(['inflation', 'jobs', 'output']) 
count_words_in_dir('./', words, action=print_summary) 
+0

上面哪些变量需要替换?我需要把我的具体目录放在哪里? – CoS 2013-02-17 22:19:43

+0

Rob,你能告诉我在上面的代码中我应该把我正在工作的目录文件夹和我感兴趣的单词列表放在哪里?我不知道我必须将其放入您定义的3个函数中。 – CoS 2013-02-17 23:15:14

+1

要处理的目录路径是函数count_words_in_dir()的第一个参数。查看代码的最后一行。你的一组目标词是同一个函数的第二个参数。看倒数第二行。 – 2013-02-18 10:15:29

一个简单的功能码数字频率在一个文本文件:

{ 
import string 

def process_file(filename): 
hist = dict() 
f = open(filename,'rb') 
for line in f: 
    process_line(line,hist) 
return hist 

def process_line(line,hist): 

line = line.replace('-','.') 

for word in line.split(): 
    word = word.strip(string.punctuation + string.whitespace) 
    word.lower() 

    hist[word] = hist.get(word,0)+1 

hist = process_file(filename) 
print hist 
}