这应该是一个简单的问题,但我就是无法理解它。我有一本名为 TD
的字典。 TD
的 {key1{key2:values}} 为 {1:{u'word':3, u'next':2, u'the':2},2: {...}...}
其中 key1
是文档,key2
是文档中的单词,value
是该单词在文档中出现的次数,使用 Counter
方法获得。
我有大量文档,因此每个文档在 TD 中都有一个条目:
TD = {1:{u'word':2, u'next':1, u'the':5,...},
2:{u'my':4, u'you':1, u'other':2,...},
...
168:{u'word':1, u'person':1, u'and':8,...}}
我现在想要做的是检查 {1{...}}
中的每个单词,看看它是否出现在其他文档中,并对每个文档重复此过程。对于每个出现单词的文档,freq
都会增加 1。我有一个名为 Score
的新字典,它应该如下所示:
{1:{u'word':score, u'next':score,...}, 2:{u'my':score, u'you':score,...}...}
要获取这本词典:
Score={}
count = 0
for x,i in TD[count].iteritems():
freq=1
num=1
for y in TD[num].keys():
if word in TF[num].keys():
freq+=1
num+=1
Score[num]={x:(i*freq)}
num+=1
这给了我以下输出:
{1:{u'word':score}, 2:{u'next':score}, 3:{u'the':score}...}
应该是:
{1:{u'word':score, u'next':score, u'the':score,...}...}
我认为问题出在行 Score[num]={x:(i*freq)}
最佳答案
使用dict views找到文档之间的交集,然后使用计数器来计算它们的频率:
Score = {}
for id, document in TD.iteritems():
counts = Score[id] = Counter()
for otherid, otherdocument in TD.iteritems():
if otherid == id:
continue # Skip current document
counts.update(document.viewkeys() & otherdocument.viewkeys())
分数中的每个条目都将计算文档中每个单词在其他文档中出现的频率。
如果您还需要在当前文档中包含字数统计 (count + 1),只需删除 if otherid == id
测试即可。
在您自己的代码中,您混淆了 num
和 count
,但在 python 中,您通常不需要手动增加循环计数器任何情况。
关于python - 用 python 更新我的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11783067/