【发布时间】:2013-12-23 02:48:23
【问题描述】:
我是 Python 新手,所以请耐心等待,但我尝试创建一个脚本,如果我还没有单词的同义词并以 JSON 格式将其添加到我的字典中。
p>这是我的代码:
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 <module>
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"]
}
}
}
【问题讨论】:
-
不是问题的原因,但是你的
isInDict()函数可以简化为return value in tempString。 -
@MartijnPieters 谢谢!
标签: python json python-3.x dictionary