使用googletrans模块检查语言代码是否有效



我试过这个代码

import googletrans
import bookDescription
bookList = ["Harry Potter", "The Alchemist", "The Hound of The Baskervilles", "Rich Dad Poor Dad"]
bookDescriptionDict = {
bookList[0]: bookDescription.harry_potter,
bookList[1]: bookDescription.the_alchemist,
bookList[2]: bookDescription.the_hound_of_the_baskervilles,
bookList[3]: bookDescription.rich_dad_and_poor_dad,
}
def checkForValidLanguageCode(langCode):
if langCode in googletrans.LANGCODES[langCode]:
return True
return False
preferedLangCodeInp = input("Enter the language you prefer to read in (Language Codes only): ")
isValid = checkForValidLanguageCode(preferedLangCodeInp)
if isValid:
print(f"Ok, you preferred language is {googletrans.LANGCODES[preferedLangCodeInp]}.")
else:
print("That's not a valid language code!")

让我稍微解释一下我有一份书单和一本附有书目说明的字典。bookDescription是一个包含描述的小文件。现在,我想使用checkForValidLanguageCode函数来检查langCode参数是否是有效的语言代码。所以,当我输入en时,它会给我这个错误

Traceback (most recent call last):
File "C:UsersDEBARKA NASKARDesktopSkillathon-Projectshelp-your-friendsmain.py", line 19, in <module>
isValid = checkForValidLanguageCode(preferedLangCodeInp)
File "C:UsersDEBARKA NASKARDesktopSkillathon-Projectshelp-your-friendsmain.py", line 14, in checkForValidLanguageCode   
if langCode in googletrans.LANGCODES[langCode]: return True
KeyError: 'en'

为什么我得到这个错误?我不明白。任何帮助都很感激:p

要检查给定的语言代码是否存在,您可以尝试以下代码:

import googletrans
import bookDescription
preferedLang=''
bookList = ["Harry Potter", "The Alchemist", "The Hound of The Baskervilles", "Rich Dad Poor Dad"]
bookDescriptionDict = {
bookList[0]: bookDescription.harry_potter,
bookList[1]: bookDescription.the_alchemist,
bookList[2]: bookDescription.the_hound_of_the_baskervilles,
bookList[3]: bookDescription.rich_dad_and_poor_dad,
}
def checkForValidLanguageCode(langCode):
data=googletrans.LANGCODES
for key, value in data.items():
if value == langCode:
global preferedLang
preferedLang=key
return True
return False
preferedLangCodeInp = input("Enter the language you prefer to read in (Language Codes only): ")
isValid = checkForValidLanguageCode(preferedLangCodeInp)
if isValid:
print(f"Ok, you preferred language is {preferedLang}.")
else:
print("That's not a valid language code!")

在你的代码中,你试图传递语言代码作为' googletrans.LANGCODES[langCode] '的参数。googletrans.LANGCODES返回JSON,其中key为语言名,value为语言码。

相关内容

  • 没有找到相关文章

最新更新