1

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

2 に答える 2

0

with open(f) as filf の内容が何であれ、fil を代入します。後で辞書のエントリにアクセスするとき

total=sum(math.log(prob)*d2[fil][word].values())

私はあなたが意味すると信じています

total = sum(math.log(prob)*d2[f][word])

ただし、これはあなたが期待していた順序と完全に一致していないようです。そのため、代わりに次のようなものを提案します。

word_list = [#list of words]
file_list = [#list of files]
dictionary = {#your dictionary}
summation = lambda file_name,prob: sum([(math.log(prob)*dictionary[word][file_name]) for word in word_list])
return_value = []
for file_name in file_list:
    prob = #something
    return_value.append(summation(file_name))

そこにある合計行は、python 内で無名関数を定義しています。これらはラムダ関数と呼ばれます。基本的に、その行が特に意味することは次のとおりです。

summation = lambda file_name,prob:

以下とほぼ同じです。

def summation(file_name, prob):

その後

sum([(math.log(prob)*dictionary[word][file_name]) for word in word_list])

以下とほぼ同じです。

result = []
for word in word_list:
    result.append(math.log(prob)*dictionary[word][file_name]
return sum(result)

合計で次のようになります。

    summation = lambda file_name,prob: sum([(math.log(prob)*dictionary[word][file_name]) for word in word_list])

それ以外の:

def summation(file_name, prob):
    result = []
    for word in word_list:
        result.append(math.log(prob)*dictionary[word][file_name])
    return sum(result)

ただし、リスト内包表記を使用したラムダ関数は、for ループの実装よりもはるかに高速です。リスト内包表記の代わりに for ループを使用する必要がある Python のケースはほとんどありませんが、確かに存在します。

于 2013-07-03T19:45:52.853 に答える
0
for fil in list2:  #list2 contains the filenames
    total = 0
    for k,v in d[fil].iteritems():
        total += v*log(prob[k])  #where prob is a dict

    print "Total of {} is {}".format(fil,total)
于 2013-07-03T19:45:58.227 に答える