2013-02-17 19 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') 

「インフレ」、「ジョブ」、「出力」個人の頻度を取得するのはあまりにも面倒です。これらの単語をリストに入れて、リスト内のすべての単語の頻度を同時に見つけることはできますか?基本的にthisと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スプレッドシートに貼り付ける+コピーすることができた場合にもいいだろう。

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()私はあなたの問題を理解していればこれをカバーしています。

docsの例があなたの問題と一致しているようです。

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

EDIT素朴なアプローチを。

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

+0

上記の例は、私のテキストファイル内のユニークな単語すべて(私の場合は3000以上のユニークな単語)を集計します。私は、テキストファイルに10〜20個の特定の単語の集計が必要です。 – CoS

+0

私はそれがリストのために働くと思う、大変ありがとう!私は時間カウンターのページでhaha – CoS

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

+0

Rob、上記のコードで私が作業しているディレクトリフォルダと私が興味を持っている単語のリストをどこに置くべきか教えてください。あなたが定義した3つの関数に何を入れなければならないのか分かりません。 – CoS

+1

処理したいディレクトリへのパスは、関数 'count_words_in_dir()'の最初の引数です。コードの最後の行を参照してください。ターゲット・ワードのセットは、同じ関数の2番目の引数です。最後から2番目の行を参照してください。 –

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 
} 
関連する問題