Python 打印jsonfile键,使其';s值由输入选择
我有以下代码和问题,任何想法都会有帮助。谢谢 nomes.json:Python 打印jsonfile键,使其';s值由输入选择,python,json,python-3.x,Python,Json,Python 3.x,我有以下代码和问题,任何想法都会有帮助。谢谢 nomes.json: { "hello":["hi","hello"], "beautiful":["pretty","lovely","handsome","attractive","gorgeous","beautiful"], "brave":["fearless","daring","valiant","valorous","brave"], "big":["huge","large","big"] } example for input
{
"hello":["hi","hello"],
"beautiful":["pretty","lovely","handsome","attractive","gorgeous","beautiful"],
"brave":["fearless","daring","valiant","valorous","brave"],
"big":["huge","large","big"]
}
example for input = one of keys :
>> xinput = 'hello' >> hello
>> 'hi' or 'hello' >> hi
example for input = one of values :
>> xinput = 'pretty' >> pretty
>> it should print it's key (beautiful) but it prints the first key (hello) >> hello
Python文件:这段代码将从json文件中查找单词同义词并打印它们
import random
import json
def allnouns(xinput):
data = json.load(open('Nouns.json'))
h = ''
items = []
T = False
for k in data.keys():
if k == xinput:
T = True
if T == True:
for item in data[xinput]:
items.append(item)
h = random.choice(items)
else:
for k in data.keys():
d = list(data.values())
ost = " ".join(' '.join(x) for x in d)
if xinput in ost:
j = ost.split()
for item in j:
if item == xinput :
h = k
break
else:
pass
else :
h = xinput
print(h)
xinput = input(' input : ')
allnouns(xinput)
示例:
{
"hello":["hi","hello"],
"beautiful":["pretty","lovely","handsome","attractive","gorgeous","beautiful"],
"brave":["fearless","daring","valiant","valorous","brave"],
"big":["huge","large","big"]
}
example for input = one of keys :
>> xinput = 'hello' >> hello
>> 'hi' or 'hello' >> hi
example for input = one of values :
>> xinput = 'pretty' >> pretty
>> it should print it's key (beautiful) but it prints the first key (hello) >> hello
问题是示例的最后一行
有没有办法解决这个问题?这看起来太复杂了。为什么不这样做呢:
import json
def allnouns(xinput):
nouns = json.load(open('Nouns.json'))
for key, synonyms in nouns.items():
if xinput in synonyms:
print(key)
return;
xinput = input(' input : ')
allnouns(xinput)
这个答案是一个巨大进步的另一个原因;所有的名字都很清楚,这使它更容易阅读。我想如果你使用更具描述性的变量名,而不是单个字母,这将对你(以及任何阅读你代码的人)有所帮助。很抱歉,我不知道如何编写脚本,我只是搜索并附加东西!!!!你用这个代码救了我:))你应该花点时间试着理解每一行都在做什么,这样你就可以避免像你原来的问题那样创建意大利面代码