14

単語の頻度を数えるためにプロジェクトをスピードアップしようとしています。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')

「インフレ」、「ジョブ」、「出力」の頻度を個別に取得するには面倒です。これらの単語をリストに入れて、リスト内のすべての単語の頻度を同時に見つけることはできますか?基本的にこれは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

ありがとう!

4

4 に答える 4

20

私があなたの問題を理解していれば、 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
于 2013-02-17T13:15:07.257 に答える
5

1つの可能な実装(Counterを使用)...

出力を印刷する代わりに、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)
于 2013-02-17T14:12:24.810 に答える
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
}
于 2016-02-19T20:05:42.760 に答える
0
import re, os, sys, codecs, fnmatch
import decimal
import zipfile
import glob
import csv

path= 'C:\\Users\\user\\Desktop\\sentiment2020\\POSITIVE'

files=[]
for r,d,f in os.walk(path):
    for file in f:
        if'.txt' in  file:
            files.append(os.path.join(r,file))

for f in files:
    print(f)
    file1= codecs.open(f,'r','utf8',errors='ignore')
    content=file1.read()

words=content.split()
for x in words:
    print (x)

dicts=[]
if __name__=="__main__":  
    str =words
    str2 = [] 
    for i in str:              
        if i not in str2: 
              str2.append(i)  
    for i in range(0, len(str2)):
        a= {str2[i]:str.count(str2[i])}
        dicts.append(a)
for i in dicts:        
    print(dicts)



#  for i in range(len(files)):
  #    with codecs.open('C:\\Users\\user\\Desktop\\sentiment2020\\NEGETIVE1\\sad1%s.txt' % i, 'w',"utf8") as filehandle:
  #         filehandle.write('%s\n' % dicts) 
于 2020-04-12T03:05:45.463 に答える