Python:如何更新嵌套字典中键值对的值?
我正在尝试制作一个反向文档索引,因此我需要知道在一组文档中,所有独特的单词出现在哪些文档里,以及它们出现的频率。
我使用了这个答案来创建一个嵌套字典。这个解决方案运行得很好,但有一个问题。
首先,我打开文件并制作一个独特单词的列表。然后,我想把这些独特的单词与原始文件进行比较。当找到匹配时,频率计数器应该更新,并把它的值存储在一个二维数组中。
最终输出应该看起来像这样:
word1, {doc1 : freq}, {doc2 : freq} <br>
word2, {doc1 : freq}, {doc2 : freq}, {doc3:freq}
etc....
问题是我无法更新字典变量。当我尝试这样做时,我得到了一个错误:
File "scriptV3.py", line 45, in main
freq = dictionary[keyword][filename] + 1
TypeError: unsupported operand type(s) for +: 'AutoVivification' and 'int'
我觉得我需要以某种方式将AutoVivification的实例转换为整数……
该怎么做呢?
提前谢谢你
我的代码:
#!/usr/bin/env python
# encoding: utf-8
import sys
import os
import re
import glob
import string
import sets
class AutoVivification(dict):
"""Implementation of perl's autovivification feature."""
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
def main():
pad = 'temp/'
dictionary = AutoVivification()
docID = 0
for files in glob.glob( os.path.join(pad, '*.html') ): #for all files in specified folder:
docID = docID + 1
filename = "doc_"+str(docID)
text = open(files, 'r').read() #returns content of file as string
text = extract(text, '<pre>', '</pre>') #call extract function to extract text from within <pre> tags
text = text.lower() #all words to lowercase
exclude = set(string.punctuation) #sets list of all punctuation characters
text = ''.join(char for char in text if char not in exclude) # use created exclude list to remove characters from files
text = text.split() #creates list (array) from string
uniques = set(text) #make list unique (is dat handig? we moeten nog tellen)
for keyword in uniques: #For every unique word do
for word in text: #for every word in doc:
if (word == keyword and dictionary[keyword][filename] is not None): #if there is an occurence of keyword increment counter
freq = dictionary[keyword][filename] #here we fail, cannot cast object instance to integer.
freq = dictionary[keyword][filename] + 1
print(keyword,dictionary[keyword])
else:
dictionary[word][filename] = 1
#extract text between substring 1 and 2
def extract(text, sub1, sub2):
return text.split(sub1, 1)[-1].split(sub2, 1)[0]
if __name__ == '__main__':
main()
9 个回答
0
if (word == keyword and dictionary[keyword][filename] is not None):
我觉得那样用是不对的,试试这个:
if (word == keyword and filename in dictionary[keyword]):
因为,检查一个不存在的键会引发 KeyError 错误。所以你必须先检查这个键在字典里是否存在...
2
我同意你应该避免使用额外的类,尤其是 __getitem__
这个方法。因为小错误可能会让 __getitem__
或 __getattr__
的调试变得非常麻烦。
Python 的 dict
对于你正在做的事情来说,似乎已经足够强大了。
那你觉得直接用 dict.setdefault
怎么样呢?
for keyword in uniques: #For every unique word do
for word in text: #for every word in doc:
if (word == keyword):
dictionary.setdefault(keyword, {})
dictionary[keyword].setdefault(filename, 0)
dictionary[keyword][filename] += 1
当然,这里的 dictionary
只是一个 dict
,而不是来自 collections
的东西或者你自己定义的类。
再说,这不就是:
for word in text: #for every word in doc:
dictionary.setdefault(word, {})
dictionary[word].setdefault(filename, 0)
dictionary[word][filename] += 1
没有必要去隔离唯一的实例,因为字典本身就强制要求唯一的键。
6
你可以用Python里的collections.defaultdict来代替自己创建一个AutoVivification类,然后再把字典实例化成那种类型的对象。
import collections
dictionary = collections.defaultdict(lambda: collections.defaultdict(int))
这样做会创建一个字典的字典,默认值是0。当你想要增加某个条目的值时,可以使用:
dictionary[keyword][filename] += 1