def makecounter():
return collections.defaultdict(int)
class RankedIndex(object):
def __init__(self):
self._inverted_index = collections.defaultdict(list)
self._documents = []
self._inverted_index = collections.defaultdict(makecounter)
def index_dir(self, base_path):
num_files_indexed = 0
allfiles = os.listdir(base_path)
self._documents = os.listdir(base_path)
num_files_indexed = len(allfiles)
docnumber = 0
self._inverted_index = collections.defaultdict(list)
docnumlist = []
for file in allfiles:
self.documents = [base_path+file] #list of all text files
f = open(base_path+file, 'r')
lines = f.read()
tokens = self.tokenize(lines)
docnumber = docnumber + 1
for term in tokens:
if term not in sorted(self._inverted_index.keys()):
self._inverted_index[term] = [docnumber]
self._inverted_index[term][docnumber] +=1
else:
if docnumber not in self._inverted_index.get(term):
docnumlist = self._inverted_index.get(term)
docnumlist = docnumlist.append(docnumber)
f.close()
print '\n \n'
print 'Dictionary contents: \n'
for term in sorted(self._inverted_index):
print term, '->', self._inverted_index.get(term)
return num_files_indexed
return 0
我执行这段代码时遇到了索引错误:列表索引超出范围。
以上代码生成一个字典索引,将“term”作为键存储,将该术语出现的文档编号存储为列表。 例如:如果单词“cat”在1.txt、5.txt和7.txt中出现,则字典将具有: cat <- [1,5,7]
现在,我必须修改它以添加术语频率,因此如果单词“cat”在文档1中出现两次,在文档5中出现三次,在文档7中出现一次: 期望结果: term <-[[docnumber, term freq], [docnumber,term freq]] <-- 一个字典中的列表! cat <- [[1,2],[5,3],[7,1]]
我尝试过对代码进行更改,但是没有任何效果。我不知道如何修改此数据结构以实现上述目标。
提前感谢您的帮助。
indexdir
方法中(假设它确实是一个方法),你以上面发布的缩进完全错误,你完全破坏了之前分配给self._inverted_index
的任何内容,并将其分配给了你之前错误的数据结构,从而使你对代码的编辑完全无关紧要。你确实意识到当你执行self.a = b
时,不管之前是否有任何东西分配给self.a
,它都毫无意义,对吗?! - Alex Martelli