在python中的嵌套字典中查找值之和
我有大约20000个文本文件,编号为5.txt、10.txt等等 我将这些文件的文件路径存储在我创建的列表“list2”中 我还有一个文本文件“temp.txt”,里面有500个单词的列表在python中的嵌套字典中查找值之和,python,dictionary,python-3.x,machine-learning,python-3.3,Python,Dictionary,Python 3.x,Machine Learning,Python 3.3,我有大约20000个文本文件,编号为5.txt、10.txt等等 我将这些文件的文件路径存储在我创建的列表“list2”中 我还有一个文本文件“temp.txt”,里面有500个单词的列表 vs mln money 等等 我将这些单词存储在我创建的另一个列表“list”中 现在我创建了一个嵌套字典d2[file][word]=在“file”中“word”的频率计数 现在, 我需要对每个文本文件重复这些单词 我正在尝试获得以下输出: filename.txt- sum(d[filename][w
vs
mln
money
等等
我将这些单词存储在我创建的另一个列表“list”中
现在我创建了一个嵌套字典d2[file][word]=在“file”中“word”的频率计数
现在,
我需要对每个文本文件重复这些单词
我正在尝试获得以下输出:
filename.txt- sum(d[filename][word]*log(prob))
在这里,filename.txt的格式是5.txt、10.txt等等
“prob”,这是我已经获得的值
我基本上需要找到每个外部键(文件)的内部键(单词)值的总和(单词的频率)
说:
这里的“the”是我的单词,“5.txt”是文件。现在6是“the”在“5.txt”中出现的次数
同样地:
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))
将open(f)作为fil
将fil分配给f的任何内容。当您以后访问字典中的条目时
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中定义了一个匿名函数。这些函数称为lambda函数。基本上,这条线的具体含义是:
summation = lambda file_name,prob:
与以下内容几乎相同:
def summation(file_name, prob):
result = []
for word in word_list:
result.append(math.log(prob)*dictionary[word][file_name]
return sum(result)
然后
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)
因此,你总共有:
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)
尽管具有列表理解的lambda函数比for循环实现快得多。python中很少有使用for循环而不是列表理解的情况,但它们确实存在。
float(d2[fil].values())
:dict.values
返回的是列表而不是数字,因此对其应用float()
也是一个错误。是的,我已经纠正了它!但关键的错误是,老实说,我不知道你在问什么。你能发布一个说明你的问题的最小的代码示例吗?试着把你发布的代码降到绝对最小。让你展示的每一行都能真实地说明你的问题。当问题可以在10中显示时,没有人愿意阅读50多行代码。@SlaterTyranus:比如,d['the']['5.txt']=6,这里“the”是我的单词,“5.txt”是文件。现在6是“the”在“5.txt”中出现的次数。同样,d['as']['5.txt']=2。我有大约100个文件,对于每个文件,我需要找到字典值的总和。因此,这里是5.txt:我需要我的答案是“6+2=8”。我需要对所有文件都这样做。但我需要的总和是(dic.values()*log(prob))…它不起作用,因为它是不受支持的操作数type@PokerFace我建议您发布一些示例数据和预期输出,因为问题非常不清楚。很抱歉,我已经编辑了我的代码,请你现在检查一下,希望它清楚!每个单词都有一个关联的概率“prob”,所以在这里,我应该考虑prob(k)是一个键值为k=word的字典吗?@PokerFace是的,dict将是这里具有word:prob
对的最佳数据结构。我在这行中得到一个类型错误:summation=lambda file\u name,prob:sum([math.log(prob)*dictionary[word][“file\u name”]对于word_列表中的word),它说:(lambda)()缺少1个必需的位置参数:'prob'行:summation=lambda file_name,prob:sum([math.log(prob)*dictionary[word][“file_name”]for word_列表中的word])意味着什么?@PokerFace我想这个键错误是因为没有任何键与文件内容相等,因为那是一根奇怪的长弦。因此,这一行中的f
而不是fil
:return sum(result),为什么它会说无效语法?我使用的是python3@PokerFace哦,上面那行有一个缺了的帕伦。
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)