[英]Python - Finding word frequencies of list of words in text file
我正在嘗試加快我的項目來計算詞頻。 我有 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
謝謝!
如果我理解你的問題, 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
一種可能的實現(使用計數器)...
我認為寫入 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)
一個簡單的函數代碼來計算文本文件中的詞頻:
{
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
}
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.