3
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

执行此代码时出现索引错误:列表索引超出范围。

上面的代码生成一个字典索引,该索引将“术语”存储为键,并将术语出现在其中的文档编号存储为列表。例如:如果“cat”一词出现在文档 1.txt、5.txt 和 7.txt 中,则字典将具有:cat <- [1,5,7]

现在,我必须修改它以添加词频,所以如果单词 cat 在文档 1 中出现两次,在文档 5 中出现三次,在文档 7 中出现一次:预期结果:term <-[[docnumber, term freq], [docnumber, term freq]] <-- 字典中的列表列表!!!猫 <- [[1,2],[5,3],[7,1]]

我玩弄了代码,但没有任何效果。我不知道要修改此数据结构以实现上述目的。

提前致谢。

4

3 回答 3

6

首先,使用工厂。从...开始:

def makecounter():
    return collections.defaultdict(int)

和以后使用

self._inverted_index = collections.defaultdict(makecounter)

作为for term in tokens:循环,

        for term in tokens:  
                self._inverted_index[term][docnumber] +=1

这会在每个字典中留下self._inverted_index[term]一个,例如

{1:2,5:3,7:1}

在你的例子中。由于您希望在每个self._inverted_index[term]列表中添加一个列表,因此在循环结束后添加:

self._inverted_index = dict((t,[d,v[d] for d in sorted(v)])
                            for t in self._inverted_index)

一旦制成(这种方式或任何其他方式——我只是展示一种简单的方式来构建它!),这个数据结构实际上会像你不必要地让它难以构建一样难用,当然( dict 更有用,更易于使用和构建),但是,嘿,一个人的肉 &c;-)。

于 2010-10-05T03:14:44.930 回答
1

这是您可以使用的通用算法,但您需要调整一些代码来适应它。它生成一个包含每个文件的字数字典的字典。

filedicts = {}
for file in allfiles:
  filedicts[file] = {}

  for term in terms:
    filedict.setdefault(term, 0)
    filedict[term] += 1
于 2010-10-05T03:09:32.390 回答
0

也许您可以为 (docname, frequency) 创建一个简单的类。

然后你的 dict 可以有这个新数据类型的列表。您也可以创建一个列表列表,但单独的数据类型会更简洁。

于 2010-10-05T03:06:17.127 回答