gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:28:31 25 4
gpt4 key购买 nike

我正在尝试制作一个反向文档索引,因此我需要从集合中的所有唯一单词中了解它们出现在哪个文档中以及出现的频率。

我用过this按顺序回答两个创建嵌套字典。提供的解决方案工作正常,但有一个问题。

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

输出最终应该是这样的:

word1, {doc1 : freq}, {doc2 : freq} <br>
word2, {doc1 : freq}, {doc2 : freq}, {doc3:freq}
etc....

问题是我无法更新字典变量。尝试这样做时出现错误:

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

我想我需要以某种方式将 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)
except KeyError:
value = self[item] = type(self)()
return value

def main():
pad = 'temp/'
dictionary = AutoVivification()
docID = 0
for files in glob.glob( os.path.join(pad, '*.html') ): #for all files in specified folder:
docID = docID + 1
filename = "doc_"+str(docID)
text = open(files, 'r').read() #returns content of file as string
text = extract(text, '<pre>', '</pre>') #call extract function to extract text from within <pre> tags
text = text.lower() #all words to lowercase
exclude = set(string.punctuation) #sets list of all punctuation characters
text = ''.join(char for char in text if char not in exclude) # use created exclude list to remove characters from files
text = text.split() #creates list (array) from string
uniques = set(text) #make list unique (is dat handig? we moeten nog tellen)

for keyword in uniques: #For every unique word do
for word in text: #for every word in doc:
if (word == keyword and dictionary[keyword][filename] is not None): #if there is an occurence of keyword increment counter
freq = dictionary[keyword][filename] #here we fail, cannot cast object instance to integer.
freq = dictionary[keyword][filename] + 1
print(keyword,dictionary[keyword])
else:
dictionary[word][filename] = 1

#extract text between substring 1 and 2
def extract(text, sub1, sub2):
return text.split(sub1, 1)[-1].split(sub2, 1)[0]

if __name__ == '__main__':
main()

最佳答案

可以使用 Python 的 collections.defaultdict 而不是创建 AutoVivification 类,然后将字典实例化为该类型的对象。

import collections
dictionary = collections.defaultdict(lambda: collections.defaultdict(int))

这将创建一个默认值为 0 的字典。当您希望增加一个条目时,请使用:

dictionary[keyword][filename] += 1

关于Python:如何更新嵌套字典中键值对的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5079790/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com