gpt4 book ai didi

python - 使用字典、Python 的简单翻译器?

转载 作者:太空宇宙 更新时间:2023-11-03 13:39:34 24 4
gpt4 key购买 nike

我正在使用 dict 来存储一个文本文件,其中第一个是英语单词,然后是西类牙语单词。

我想让它做的是能够搜索一个词(英语单词),然后将其翻译成西类牙语。我不确定为什么每次输入要翻译的单词时都会返回 None 。

我使用的是 python3,如果有区别的话。

def getDict():
myDict = {}

for line in open("eng2sp.txt"):
for n in line:
(eng,span) = line.split()
myDict[eng] = span


print("Translate from English to Spanish")
word = input("Enter the english word to translate:")

print(search(myDict,word))



def search(myDict,lookup):
for key, value in myDict.items():
for v in value:
if lookup in v:
return



def main():
getDict()


main()

输出:

enter image description here

最佳答案

这可以更简单:

def search(myDict,lookup):
if lookup in myDict:
return myDict[lookup]
return "NOT FOUND"

此代码将为大型词典提供更好的性能。当找不到该项目时,您可能希望返回 None 而不是字符串,这取决于您希望如何处理这种情况。

关于python - 使用字典、Python 的简单翻译器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34012512/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com