【问题标题】:Python Dictionary from External file来自外部文件的 Python 字典
【发布时间】:2016-07-09 09:56:22
【问题描述】:

我正在尝试用 Python 制作字典,但我不知道如何做两件事。

  1. 当我在字典中搜索关键字时,我希望它能够找到其中包含关键字的每个单词,而不是直接查找匹配项。例如。搜索:猫 - 结果:猫,分配。

  2. 我希望词典加载一个外部文件,以便以后加载时可以保存我添加到词典中的新术语。

【问题讨论】:

  • 你的代码有问题吗?
  • 当我搜索 cat 时,它只会找到 Cat,而不是 cat and allocate。关闭文件后,我添加到字典中的新结果不会保存。
  • 你可以遍历字典键并检查它是否包含单词。
  • 您需要打开一个文件,在文件上写入字典内容,然后关闭文件,以便保留字典的内容。这是因为每次启动程序时都会重新创建字典
  • 为了将来参考,尽量避免使用像dict这样的内置函数作为变量名。它使代码难以阅读,并可能导致难以诊断的错误。

标签: python arrays dictionary import external


【解决方案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",
        }

【讨论】:

    【解决方案2】:

    这应该让你在分配中匹配 cat。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-10
      • 2021-01-10
      • 2013-07-13
      • 1970-01-01
      • 1970-01-01
      • 2022-12-31
      相关资源
      最近更新 更多