私はPythonで辞書を作ろうとしていますが、私は2つのことをする方法がわかりません。 外部ファイルからのPython辞書
私は辞書でキーワードを検索
、だけではなく、直接の一致を探して、私はそれでキーワードを持っているすべての単語を見つけるためにそれをしたいと思います。例えば。検索:Cat - 結果:Cat、Allocate。私は辞書に外部ファイルをロードしたいので、後でロードするときに辞書に追加する新しい用語を保存することができます。
私はPythonで辞書を作ろうとしていますが、私は2つのことをする方法がわかりません。 外部ファイルからのPython辞書
私は辞書でキーワードを検索
、だけではなく、直接の一致を探して、私はそれでキーワードを持っているすべての単語を見つけるためにそれをしたいと思います。例えば。検索:Cat - 結果:Cat、Allocate。私は辞書に外部ファイルをロードしたいので、後でロードするときに辞書に追加する新しい用語を保存することができます。
これにより、catとallocateを一致させることができます。
for key in dict.keys():
if x in key:
do some stuff
次の方法を使用することができます。
2については
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()
1の場合:あなたは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",
}
そして、あなたのコードに問題がありますか? – Jacobr365
私が猫を検索すると、それは猫ではなく、猫でしか出てこない。 ファイルを閉じると、辞書に追加した新しい結果は保存されません。 – TonyShen
辞書キーをループして単語が含まれているかどうかを確認できます。 – Jacobr365