字典在迭代期间改变了大小,但我没有看到我在哪里改变它

 NANA-LS 发布于 2023-02-12 15:52

我是Python的新手,所以请耐心等待,但我已经尝试创建一个脚本,如果我还没有它,可以获取单词的同义词并将其以JSON格式添加到我的字典中.

这是我的代码:

import json, sys, urllib
from urllib.request import urlopen

f = open('dict.json', 'r')
string = json.loads(f.read())
tempString = string
url = 'http://words.bighugelabs.com/api/2/myapicode/%s/json'

def main():
    crawl()

def crawl():
    for a in string:
        for b in string[a]:
            for c in string[a][b]:
                for d in string[a][b][c]:
                    if not isInDict(d):
                        addWord(d, getWord(url % d))
                    else:
                        print('[-] Ignoring ' + d)
    f.seek(0)
    f.write(tempString)
    f.truncate()
    f.close()

def isInDict(value):
    for x in list(tempString.keys()):
        if x == value:
            return True
    return False

def getWord(address):
    try:
        return urlopen(address).read().decode('utf-8')
    except:
        print('[!] Failed to get ' + address)
    return ''

def addWord(word, content):
    if content != None and content != '':
        print('[+] Adding ' + word)
        tempString[word] = content
    else:
        print('[!] Ignoring ' + word + ': content empty')

if __name__ == '__main__':
    main()

在跑步时,它可以正常工作直到'amour'并且它给我这个:

working fine
[+] Adding sex activity
[+] Adding sexual activity
[+] Adding sexual desire
[+] Adding sexual practice
[-] Ignoring amour
Traceback (most recent call last):
  File "crawler.py", line 47, in 
    main()
  File "crawler.py", line 10, in main
    crawl()
  File "crawler.py", line 13, in crawl
    for a in string:
RuntimeError: dictionary changed size during iteration

但我没有看到我在哪里改变任何东西string,只有tempString......

PS:如果你想要我读过的JSON数据:

{
    "love": {
        "noun": {
            "syn": ["passion", "beloved", "dear", "dearest", "honey", "sexual love", "erotic love", "lovemaking", "making love", "love life", "concupiscence", "emotion", "eros", "loved one", "lover", "object", "physical attraction", "score", "sex", "sex activity", "sexual activity", "sexual desire", "sexual practice"],
            "ant": ["hate"],
            "usr": ["amour"]
        },
        "verb": {
            "syn": ["love", "enjoy", "roll in the hay", "make out", "make love", "sleep with", "get laid", "have sex", "know", "do it", "be intimate", "have intercourse", "have it away", "have it off", "screw", "jazz", "eff", "hump", "lie with", "bed", "have a go at it", "bang", "get it on", "bonk", "copulate", "couple", "like", "mate", "pair"],
            "ant": ["hate"]
        }
    }
}

Peter DeGlop.. 6

在这一行:

string = json.loads(f.read())
tempString = string

您指定tempString引用相同的字典对象string.然后,在addWord你改变tempString:

    tempString[word] = content

因为tempString只是对同一个字典对象的另一个引用,所以string它也会发生变化string.

为避免这种情况,请使用:

import copy
tempString = copy.deepcopy(string)

此外,使用类似的变量名称通常也是一种不好的做法string,也就是内置函数的名称.它不是很具描述性,当名称在范围内时,它将使您无法方便地访问内置函数.

1 个回答
  • 在这一行:

    string = json.loads(f.read())
    tempString = string
    

    您指定tempString引用相同的字典对象string.然后,在addWord你改变tempString:

        tempString[word] = content
    

    因为tempString只是对同一个字典对象的另一个引用,所以string它也会发生变化string.

    为避免这种情况,请使用:

    import copy
    tempString = copy.deepcopy(string)
    

    此外,使用类似的变量名称通常也是一种不好的做法string,也就是内置函数的名称.它不是很具描述性,当名称在范围内时,它将使您无法方便地访问内置函数.

    2023-02-12 15:54 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有