pythonpython-3.xtranslationtranslatedeepl

Autodetect and translate two or more languages ins a sentence using python


I have the following example sentence

text_to_translate1=" I want to go for swimming however the 天气 (weather) is not good"

As you can see there exist two languages in the sentence (i.e, English and Chinese).

I want a translator. The result that I want is the following:

I want to go for swimming however the weather(weather) is not good

I used the deepl translator but cannot autodetect two languages in one.

Code that I follow:

import deepl

auth_key = "xxxxx"
translator = deepl.Translator(auth_key)

result = translator.translate_text(text_to_translate1, target_lang="EN-US")
print(result.text)  
print(result.detected_source_lang) 

The result is the following:

I want to go for swimming however the 天气 (weather) is not good
EN

Any ideas?


Solution

  • I do not have access to the DeepL Translator, but according to their API you can supply a source language as a parameter:

    result = translator.translate_text(text_to_translate1, source_lang="ZH", target_lang="EN-US")
    

    If this doesn't work, my next best idea (if your target language is only English) is to send only the words that aren't English, then translate them in place. You can do this by looping over all words, checking if they are English, and if not, then translating them. You can then merge all the words together.

    I would do it like so:

    text_to_translate1 = "I want to go for swimming however the 天气 (weather) is not good"
    
    new_sentence = []
    # Split the sentence into words
    for word in text_to_translate1.split(" "):
        # For each word, check if it is English
        if not word.isascii():
            new_sentence.append(translator.translate_text(word, target_lang="EN-US").text)
        else:
            new_sentence.append(word)
    
    # Merge the sentence back together
    translated_sentence = " ".join(new_sentence)
    
    print(translated_sentence)