Python:列表列表的字典

csg*_*y11 3 python information-retrieval

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
Run Code Online (Sandbox Code Playgroud)

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

上面的代码生成一个字典索引,它将'term'存储为一个键,以及将该术语作为列表出现的文档编号.例如:如果术语'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]]

我玩了代码,但没有任何作用.我不知道修改这个数据结构来实现上述目标.

提前致谢.

Ale*_*lli 6

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

def makecounter():
    return collections.defaultdict(int)
Run Code Online (Sandbox Code Playgroud)

以后用

self._inverted_index = collections.defaultdict(makecounter)
Run Code Online (Sandbox Code Playgroud)

作为for term in tokens:循环,

        for term in tokens:  
                self._inverted_index[term][docnumber] +=1
Run Code Online (Sandbox Code Playgroud)

这留下了每个self._inverted_index[term]词典,如

{1:2,5:3,7:1}
Run Code Online (Sandbox Code Playgroud)

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

self._inverted_index = dict((t,[d,v[d] for d in sorted(v)])
                            for t in self._inverted_index)
Run Code Online (Sandbox Code Playgroud)

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