小编Jor*_*rit的帖子

Python:如何在嵌套字典中更新键值对的值?

我正在尝试制作一个反向的文档索引,因此我需要从集合中的所有独特单词中了解它们发生在哪些文档中以及发生的频率.

我已经使用这个答案,以便两个创建一个嵌套字典.提供的解决方案工作正常,但有一个问题.

首先,我打开文件并列出一个独特的单词列表.这些独特的单词我想要与原始文件进行比较.当存在匹配时,应更新频率计数器并将其值存储在二维数组中.

输出最终应该如下所示:

word1, {doc1 : freq}, {doc2 : freq} <br>
word2, {doc1 : freq}, {doc2 : freq}, {doc3:freq}
etc....
Run Code Online (Sandbox Code Playgroud)

问题是我无法更新字典变量.尝试这样做时,我收到错误:

  File "scriptV3.py", line 45, in main
    freq = dictionary[keyword][filename] + 1
TypeError: unsupported operand type(s) for +: 'AutoVivification' and 'int'
Run Code Online (Sandbox Code Playgroud)

我想我需要以某种方式将AutoVivification的实例转换为int ....

怎么去?

提前致谢

我的代码:

#!/usr/bin/env python 
# encoding: utf-8

import sys
import os
import re
import glob
import string
import sets

class AutoVivification(dict):
    """Implementation of perl's autovivification feature."""
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item) …
Run Code Online (Sandbox Code Playgroud)

python casting object autovivification

2
推荐指数
1
解决办法
4392
查看次数

标签 统计

autovivification ×1

casting ×1

object ×1

python ×1