Python: 'NoneType'对象没有属性keys

1 投票
1 回答
1791 浏览
提问于 2025-04-16 04:02
   def index_dir(self, base_path): 

        num_files_indexed = 0
        allfiles = os.listdir(base_path)
        #print allfiles
        num_files_indexed = len(allfiles)
        #print num_files_indexed
        docnumber = 0
        self._inverted_index = {} #dictionary
        for file in allfiles: 
                self.documents = [base_path+file] #list of all text files
                f = open(base_path+file, 'r')
                lines = f.read()
  # Tokenize the file into words
                tokens = self.tokenize(lines)
                docnumber = docnumber + 1
                print 'docnumber', docnumber
                for term in tokens:  
# check if the key already exists in the dictionary, if yes, 
# just add a new value for the key
                    #if self._inverted_index.has_key(term)
                    if term in sorted(self._inverted_index.keys()):
                        docnumlist = self._inverted_index.get(term)
                        docnumlist = docnumlist.append(docnumber)
                    else:
# if the key doesn't exist in dictionary, add the key (term) 
# and associate the docnumber value with it. 
                        self._inverted_index = self._inverted_index.update({term: docnumber})
   #self._inverted_index[term] = docnumber 
                f.close()
        print 'dictionary', self._inverted_index 
        print 'keys', self._inverted_index.keys()
        return num_files_indexed

我正在做一个信息检索的项目,主要是要从多个文本文件中提取信息。具体来说,就是要读取这些文件,把里面的单词分开,然后把这些单词存储在一个反向索引(字典)数据结构里。

举个例子: doc1.txt: "the dog ran" doc2.txt: "the cat slept"
反向索引的样子是这样的: _inverted_index = { 'the': [0,1], 'dog': [0], 'ran': [0], 'cat': [1], 'slept': [1] } 这里的0和1代表的是文档的ID。

我遇到了一个错误: 'Nontype'对象没有属性keys。出错的地方在第95行。

非常感谢大家的帮助。

1 个回答

3

self._inverted_index 是一个字典时,使用 self._inverted_index.update 会直接在这个字典上进行更新,并且返回 None(就像大多数会改变内容的操作一样)。所以,你代码中的严重错误在于这一行:

 self._inverted_index = self._inverted_index.update({term: docnumber})

这行代码把 self._inverted_index 设置成了 None。只需要把它改成

 self._inverted_index.update({term: docnumber})

直接接受这个更新(改变),而不进行错误的赋值就可以了!

撰写回答