Python中文
首页
教程
问答
标签
搜索
登录
注册
Python:列表列表字典
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<pre><code>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.<a href="https://www.cnpython.com/list/append" class="inner-link">append</a>(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 </code></pre> <p>执行此代码时出现索引错误:list index超出范围。在</p> <p>上面的代码生成一个字典索引,该索引将“term”存储为键,并将该术语出现的文档编号作为列表存储。 例如:如果术语“cat”出现在文档1.txt、5.txt和7.txt中,则字典将具有: 类别<;-[1,5,7]</p> <p>现在,我必须修改它以添加术语frequency,因此如果单词cat在文档1中出现两次,在文档5中出现三次,在文档7中出现一次: 预期结果: term<;-[[docnumber,term freq],[docnumber,term freq]]<;--dict中的列表列表!!! 类别<;-[[1,2],[5,3],[7,1]]</p> <p>我玩弄了一下代码,但什么也没用。我不知道如何修改这个数据结构来实现上述目的。在</p> <p>提前谢谢。在</p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>这里有一个通用的算法,您可以使用,但您需要调整一些代码来适应它。 它生成一个dict,其中包含每个文件的字数字典。在</p> <pre><code>filedicts = {} for file in allfiles: filedicts[file] = {} for term in terms: filedict.setdefault(term, 0) filedict[term] += 1 </code></pre>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
如何合并多个PDF文件?
9 回答
如何合并多个xarray数据变量及其坐标?
6 回答
如何合并多个列中具有重复值的行
9 回答
如何合并多个唯一id
9 回答
如何合并多个图纸并使用图纸名称的名称重命名列名?
10 回答
如何合并多个字典并添加同一个键的值?(Python)
4 回答
如何合并多个搜索结果文件(pkl)以将它们全部打印在一起?
7 回答
如何合并多个数据帧
2 回答
如何合并多个数据帧并使用Pandas为假人添加列?
10 回答
如何合并多个数据帧并按时间戳排序
9 回答
如何合并多个数据帧的列表并用另一个lis标记每列
6 回答
如何合并多个数据框中的列
1 回答
如何合并多个文件?
7 回答
如何合并多个查询集?
2 回答
如何合并多个绘图?
3 回答
如何合并多个词典
7 回答
如何合并多个输入数据集(数据帧)?
5 回答
如何合并多条记录中拆分的文本行
1 回答
如何合并多索引列datafram
4 回答
如何合并多级(即多索引)数据帧?
6 回答