Python:列表列表字典

2024-06-25 23:06:17 发布

您现在位置:Python中文网/ 问答频道 /正文

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

执行此代码时出现索引错误:list index超出范围。在

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

现在,我必须修改它以添加术语frequency,因此如果单词cat在文档1中出现两次,在文档5中出现三次,在文档7中出现一次: 预期结果: term<;-[[docnumber,term freq],[docnumber,term freq]]<;--dict中的列表列表!!! 类别<;-[[1,2],[5,3],[7,1]]

我玩弄了一下代码,但什么也没用。我不知道如何修改这个数据结构来实现上述目的。在

提前谢谢。在


Tags: pathin文档ltselfbaseindexfiles
3条回答

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

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

  for term in terms:
    filedict.setdefault(term, 0)
    filedict[term] += 1

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

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

首先,使用工厂。开始于:

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

以及以后使用

^{pr2}$

作为for term in tokens:循环

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

这将在每个self._inverted_index[term]中留下一个dict,例如

{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的dict更有用、更易于使用和构造),但是,嘿,一个人的男人肉&c;-)。在

相关问题 更多 >