2016-03-22 78 views
1

我想在Python中製作字典,但我不知道如何做兩件事。來自外部文件的Python字典

  1. 當我在字典中搜索關鍵字時,我不希望直接匹配,而是希望找到每個包含關鍵字的單詞。例如。搜索:貓 - 結果:貓,分配。

  2. 我希望字典加載一個外部文件,因此我添加到字典中的新術語可以在以後加載時保存。

+0

並與你的代碼的問題是什麼? – Jacobr365

+0

當我搜索貓,它只會提出貓,而不是貓和分配。 關閉我的文件後,我添加到字典中的新結果不會保存。 – TonyShen

+0

您可以循環查看字典鍵並檢查它是否包含該字詞。 – Jacobr365

回答

0

這應該讓你匹配貓在分配。

for key in dict.keys(): 
    if x in key: 
     do some stuff 
1

您可以使用下面的方法:
對於1

print ("Welcome back to the dictionary"); 

dict = {"CAT": "A small four legged animal that likes to eat mice", 
     "DOG": "A small four legged animal that likes to chase cats", 
     "ALLOCATE": "to give something to someone as ​their ​share of a ​total ​amount, to use in a ​particular way", 
     } 

def Dictionary(): 
    x = input("\n\nEnter a word: \n>>>"); 
    x = x.upper(); 
    found = False 
    for y in dict: 
     if x in y: 
      found = True 
      print (x,":",dict[x]) 
      Dictionary() 
      break 
    if not found: 
     y = input ("Unable to find word. Enter a new definition of your word: \n>>>"); 
     dict.update({x:y}) 
     Dictionary() 
Dictionary() 

爲2:您可以直接從JSON文件加載數據

import json 
dict = {} 
with open("test.json", "r") as config_file: 
    dict = json.load(config_file) 

其中test.json是你的文件爲例如
test.json

{"CAT": "A small four legged animal that likes to eat mice", 
     "DOG": "A small four legged animal that likes to chase cats", 
     "ALLOCATE": "to give something to someone as ​their ​share of a ​total ​amount, to use in a ​particular way", 
     }