打印json文件键的值是由输入选择的

2024-05-20 11:36:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码和问题,任何想法都会有帮助。谢谢

nomes.json:

{
"hello":["hi","hello"],
"beautiful":["pretty","lovely","handsome","attractive","gorgeous","beautiful"],
"brave":["fearless","daring","valiant","valorous","brave"],
"big":["huge","large","big"]
}

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)

示例:

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

问题是示例的最后一行

有没有办法解决这个问题


Tags: injsonhelloforinputdataifpretty
1条回答
网友
1楼 · 发布于 2024-05-20 11:36:42

这看起来过于复杂了。为什么不这样做呢:

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)

相关问题 更多 >