Home > Software design >  How to set up Translator from googletrans library?
How to set up Translator from googletrans library?

Time:01-08

I am trying to parse, translate and save XML file. I am stucked with setting up Translator from googletrans library in Python (probably). Here is my code:

import xml.etree.ElementTree as ET
from googletrans import Translator

# Parse the XML file
tree = ET.parse('input.xml')

# Create a Translator object
translator = Translator(src='en', dest='sk')

# Iterate over the elements in the XML document
for elem in tree.iter():
    # Check if the element has text content
    if elem.text:
        # Translate the text content
        translated_text = translator.translate(elem.text).text
        # Update the text content of the element
        elem.text = translated_text

# Save the modified XML document to a file
tree.write('output.xml')

Here is my error: "line 8, in translator = Translator(src='en', dest='sk') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: Translator.init() got an unexpected keyword argument 'src'"

Can someone tell me, what I have wrong there? Thanks.

CodePudding user response:

I tried googletrans, but I got it not to run. I suggest translators instead, it seem more actively developed, too.

Here my test XML Input <- DE:

<?xml version="1.0" encoding="utf-8"?>
<book>
  <text>Bücher sind das Salz in der Suppe</text>
</book>

Python script according your suggestion:

import xml.etree.ElementTree as ET

import translators as ts
import translators.server as tss
from_language, to_language = 'de', 'en'

tree= ET.parse('translator_de.xml')
root = tree.getroot()

ET.dump(root)

for elem in root:
    if elem.text is not None:
        translated_text = tss.google(elem.text, from_language, to_language)
        elem.text = translated_text
        
tree.write('translator_en.xml', encoding='utf-8', xml_declaration=True)
        
ET.dump(root)

Output -> EN:

<?xml version='1.0' encoding='utf-8'?>
<book>
  <text>Books are the salt in the soup</text>
</book>
    

CodePudding user response:

You cannot use src and dest when creating an instance of Translator. Those parameters are available on the translate() method.

translator = Translator()
...
translated_text = translator.translate(elem.text, src='en', dest='sk').text

See https://py-googletrans.readthedocs.io/en/latest/#googletrans-translator.

  • Related