Search code examples
pythontranslation

Translate python not auto detecting language properly


I am currently using the translate module for this (https://pypi.org/project/translate/).

test = input(">> ")
test = test.split()
lang = test[-1].replace("-","")
del test[-1]
test = ' '.join(test)
print(lang)
print(test)
translator = Translator(from_lang='autodetect', to_lang=lang)
translation = translator.translate(test)
print(translation)

Inputting "hola -en" I should expect it to translate it to "hello" - instead it gets outputted as "hola", no change. If I do "hello -es", I should expect it to translate it to "hola", which it does.

I can't seem to figure out why translating from a language other than english does not work.

Examples:

>> hello -es
to_lang: es
input: hello
output: Hola

>> hola -en
to_lang: en
input: hola
output: hola

Solution

  • Well, I did a workaround which solves my issue but doesn't solve the autodetect issue. Adding a second argument in the user input to include the "from_lang" fixes the issue.

    test = input(">> ")
    test = test.split()
    to_lang = test[-1].replace("-","")
    from_lang = test[-2].replace("-","")
    del test[-1]
    del test[-1]
    test = ' '.join(test)
    print(from_lang,to_lang)
    print(test)
    translator = Translator(from_lang=from_lang, to_lang=to_lang)
    translation = translator.translate(test)
    print(translation)