IndexError: list index out of range (while using Googletrans API)

1.2k Views Asked by At

I'm trying to translate a yml file (which exists over 4000 lines) to dutch using the Googletrans API.

This is my python code:

from googletrans import Translator
import re

translator = Translator()

with open("Results2/ValuesfileNotTranslated.yml") as a_file: # Not translated File 
  for object in a_file:
    stripped_object = object.rstrip()
    found = False
    file = open("Results2/ValuesfileTranslated.yml", "a") #Translated file
    if not stripped_object.strip():
      file.writelines("\n")
    elif "# Do not translate" in stripped_object: #Skips lines with "# Do Not Translates"
      counter_DoNotTranslate += 1
      file.writelines(stripped_object + "\n")
    else: #Translates english to dutch
      counter_Translate += 1
      results = translator.translate(stripped_object, src='en', dest='nl')
      translatedText = results.text
      file.writelines(re.split('|=', translatedText, maxsplit=1)[-1].strip() + "\n" )

But when I try to run the code it works until line 276.

This is the YAML file I want to translate.

...
E-mail
E-Mail oder Name
Password
Toggle dropdown
Are you sure?
Yes, sure
Cancel
Back
Download
Submit
Add
Edit
Delete
Beta
"This new functionality is not yet optimized for all browsers. Please create a helpdesk ticket to inform us about errors, providing details including the browser and browser version you are using. As a workaround, we ask you to try another browser to continue (Chrome or Firefox)"

Please enable Javascript in your browser!! # This is line 276
http://www.enable-javascript.com/
Read more
Read less
Close

...

After line 276 I get this error:

Traceback (most recent call last):
  File "/Users/AndreB/Library/Mobile Documents/com~apple~CloudDocs/Work/Freelance/ProjectYML/Programma/python/vertaling.py", line 29, in <module>
    results = translator.translate(stripped_object, src='en', dest='nl') #Choose a source and a destination
  File "/Users/AndreB/Library/Python/3.9/lib/python/site-packages/googletrans/client.py", line 222, in translate
    translated_parts = list(map(lambda part: TranslatedPart(part[0], part[1] if len(part) >= 2 else []), parsed[1][0][0][5]))
IndexError: list index out of range

I can't figure out what the problem is with my code.

Does anyone have an idea how I can fix this?

1

There are 1 best solutions below

0
On

I know this is an old post but I just had this problem and found a solution. The issue was that Googletrans didn't know what to do with empty lines. I was translating by line so I just added:

if line != "\n":

before

translator.translate(line) 

That's it - it worked! You may need to modify if you're not translating by line, but that's the idea. Good luck.