print jsonfile key,它的值是通过输入选择的

时间:2016-09-13 18:19:14

标签: python json python-3.x

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

Nouns.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

问题是示例的最后一行

任何想法如何解决?

1 个答案:

答案 0 :(得分:2)

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

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)