背景:
我有一个JSON dictionary
文件,如下所示:
dictionary = {"Qui": "クイ", "Quiana": "キアナ", "Quick": "クイック", "Quickley": "クイックリー", "Quico": "キコ", "Quiej-Alvarez": "クエイ アルバレス", "Quigg": "クイッグ", "Quigley": "クイグリー", "Quijano": "クイジャーノ", "Quik": "クイック", "Quilici": "クイリチ", "Quill": "クィル"}
然后,我将让用户通过输入输入任意数量的键,最后返回结合了key.value
的格式化字符串。
问题:
到目前为止,我的代码以非常笨拙/不完整的方式完成了工作。关于如何清理代码并实现我的目标的任何建议?
当前代码:
import json
import sys, math
import codecs
#Part1
search_term,search_term2 = input("Enter a Name: ").split()
dictionary = {}
keys = dictionary.keys()
values = dictionary.values()
with open ('translation.json', 'r', encoding='utf-8-sig') as f:
term_data = json.load(f)
if search_term.casefold() in term_data:
word = search_term.title()
elif search_term.title() in term_data:
word = search_term.title()
output1 = "{}".format(term_data[search_term])
#Part 2
with open ('translation.json', 'r', encoding='utf-8-sig') as f:
term_data2 = json.load(f)
if search_term2.casefold() in term_data2:
word2 = search_term2.title()
elif search_term2.title() in term_data2:
word2 = search_term2.title()
#else:
#print("Name not found in dictionary.")
output2 = "{}".format(term_data2[search_term2])
print("{}・{}".format(output1,output2))
答案 0 :(得分:0)
您当前的代码只能输入2个不符合您的原始要求的键,我将按如下所示进行扩展,同时使其变得更简单:
test.py :
import json
import codecs
with open('translation.json', 'r', encoding='utf-8-sig') as f:
term_data = json.load(f)
search_terms = input("Enter a name: ").split()
l = [term_data[i] for i in search_terms if i.casefold() in term_data or i.title() in term_data]
print('.'.join(l))
IO
操作会很昂贵,我们需要避免一次又一次地执行该操作。Part1
,Part2
那样重复术语匹配。我们可以循环执行此操作,这里我使用list comprehension
。search_terms
for i in search_terms
循环用户输入的字词i
中候选词casefold()
的{{1}}或title()
,则将dic中的值再次放入新列表term_data
中,如果什么都不做。l
连接list的所有必需元素。输出:
.