Python - поиск слов частоты списка слов в текстовом файле
Я пытаюсь ускорить мой проект, чтобы подсчитать частоты слов. У меня есть 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 + текстовых файлов. Кажется, достаточно легко, но я немного застрял. Любая помощь?
Результат вроде бы был бы фантастическим: имя_файла1 инфляция, рабочие места, выпуск 3, 5, 1
Filename2
inflation, jobs, output
7, 2, 4
Filename3
inflation, jobs, output
9, 3, 5
Спасибо!
Ответы
Ответ 1
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)
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
Ответ 2
Одна возможная реализация (с использованием счетчика)...
Вместо того, чтобы печатать вывод, я думаю, что было бы проще записать в файл 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)
Ответ 3
Простой функциональный код для подсчета частот слов в текстовом файле:
{
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
}