5.txt、10.txt などの番号が付けられた約 20000 個のテキスト ファイルがあります。
これらのファイルのファイルパスを、作成したリスト「list2」に保存しています。
500単語のリストを含むテキストファイル「temp.txt」もあります
vs
mln
money
等々..
これらの単語を、作成した別のリスト「リスト」に保存しています。
ここで、ネストされた辞書を作成します d2[file][word]=「file」内の「word」の頻度カウント
今、
次のように、テキスト ファイルごとにこれらの単語を反復処理する必要があります。
私は次の出力を取得しようとしています:
filename.txt- sum(d[filename][word]*log(prob))
ここで、filename.txt は 5.txt、10.txt などの形式です...
「確率」、これは私がすでに取得した値です
私は基本的に、すべての外側のキー(ファイル)について、内側のキー(単語)の値(単語の頻度)の合計を見つける必要があります。
言う:
d['5.txt']['the']=6
ここで、"the" は私の単語で、"5.txt" はファイルです。6 は、"5.txt" で "the" が出現する回数です。
同様に:
d['5.txt']['as']=2.
辞書の値の合計を見つける必要があります。
だから、ここに5.txtがあります:私は私の答えが必要です:
6*log(prob('the'))+2*log(prob('as'))+...`(for all the words in list)
すべてのファイルに対してこれを行う必要があります。
私の問題は、ネストされた辞書を反復処理することになっている部分にあります
import collections, sys, os, re
sys.stdout=open('4.txt','w')
from collections import Counter
from glob import glob
folderpath='d:/individual-articles'
folderpaths='d:/individual-articles/'
counter=Counter()
filepaths = glob(os.path.join(folderpath,'*.txt'))
#test contains: d:/individual-articles/5.txt,d:/individual,articles/10.txt,d:/individual-articles/15.txt and so on...
with open('test.txt', 'r') as fi:
list2= [line.strip() for line in fi]
#temp contains the list of words
with open('temp.txt', 'r') as fi:
list= [line.strip() for line in fi]
#the dictionary that contains d2[file][word]
d2 =defaultdict(dict)
for fil in list2:
with open(fil) as f:
path, name = os.path.split(fil)
words_c = Counter([word for line in f for word in line.split()])
for word in list:
d2[name][word] = words_c[word]
#this portion is also for the generation of dictionary "prob",that is generated from file 2.txt can be overlooked!
with open('2.txt', 'r+') as istream:
for line in istream.readlines():
try:
k,r = line.strip().split(':')
answer_ca[k.strip()].append(r.strip())
except ValueError:
print('Ignoring: malformed line: "{}"'.format(line))
#my problem lies here
items = d2.items()
small_d2 = dict(next(items) for _ in range(10))
for fil in list2:
total=0
for k,v in small_d2[fil].items():
total=total+(v*answer_ca[k])
print("Total of {} is {}".format(fil,total))