2013-02-17 162 views
11

我正在加速我的項目來計算單詞頻率。我有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 

謝謝!

回答

14

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

4

一個可能實現(使用計數器)...

而不是打印輸出的,我認爲這將是簡單的寫入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

0

一個簡單的功能碼數字頻率在一個文本文件:

{ 
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 
} 
相關問題