2016-03-22 52 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", 
     }