2016-09-13 20 views
1

私は以下のコードと問題を抱えています。おかげで...jsonfileキーを入力して値を入力してください

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 

問題は最後の行です

問題を解決する方法はありますか?

答えて

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) 
+1

すべての名前は非常に明確で、読みやすくなっています。私はあなたが(そしてあなたのコードを読んでいる人なら)一文字ではなく、より説明的な変数名を使用すると助けになると思います。 –

+0

私はちょうど検索し、物事を添付スクリプトを知っていないので、ごめんなさい!あなたはこのコードで私を救った:))) – Scott

+0

あなたは元の質問のようにスパゲッティのコードを作成するのを避けるために、各行が何をしているのかを理解するために時間をかけてください – RPGillespie

関連する問題