Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When doing translation, how can I skip a row if the text is already in the target language?

I am using EasyNMT to translate from English to German. Here is my code:

import pandas as pd, warnings
from easynmt import EasyNMT

warnings.filterwarnings('ignore')
model = EasyNMT('opus-mt')

df = pd.read_excel('test.xlsx')

def en_de(x):
    x = model.translate(x, source_lang = 'en', target_lang = 'de')
    return x

df['col_tl'] = df['col1'].apply(en_de)

I want to skip rows that are in German and only translate rows that are in English. Is this possible?

Here’s the sample data, where the last row is in German:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

col1
The cat sat on the windowsill, gazing out at the birds flying by.
The sun was setting over the ocean, painting the sky with a beautiful array of orange and pink hues.
The young man walked through the park, lost in thought as he listened to his favorite music on his headphones.
The small town was nestled in the rolling hills of the countryside, its quaint streets lined with colorful houses and shops.
The old oak tree stood tall and proud, its branches reaching up to the clear blue sky.
Die Katze saß auf der Fensterbank und schaute auf die vorbeifliegenden Vögel.

>Solution :

You can use the detect_language to find the current language

def en_de(x):
    # Check the language of the input text
    language = model.detect_language(x)
    # If the language is English, translate the text
    if language == 'en':
        x = model.translate(x, source_lang = 'en', target_lang = 'de')
    return x
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading