TypeError: Translator.translate() missing 1 required positional argument: 'text'

56 Views Asked by At

Im following this tutorial to translate text from spanish to english using python googletrans but i get this error:

TypeError: Translator.translate() missing 1 required positional argument: 'text'

im using googletrans 3.0.0 and python 3.10.6

this is my code:

from googletrans import Translator, constants

translation = Translator.translate("Hola Mundo", dest="en")
print(f"{translation.origin} ({translation.src}) --> {translation.text} ({translation.dest})")

i already tried using Translator.translate(text="Hola Mundo", dest="en")

and this answer doesnt work for me, i get this error instead:

AttributeError: 'NoneType' object has no attribute 'group'

i switched to googletrans==3.1.0a0 as said in this tutorial but the error persists

Any Help Would Be Appreciated.

1

There are 1 best solutions below

0
ljdyer On BEST ANSWER

The answer you linked to is correct and the problem with your code is as described: you are calling the method from the class directly rather than creating an instance.

For future reference, in Python class names are typically written in title case without underscores (e.g. Translator, DataFrame) whereas variables such as class instances use lowercase with underscores (e.g. translator, num_entries). We more commonly (though not always) call class methods on instances of classes.

The correct code for this example is:

from googletrans import Translator, constants

translator = Translator()
translation = translator.translate("Hola Mundo", dest="en")
print(f"{translation.origin} ({translation.src}) --> {translation.text} ({translation.dest})") 

Note that translator is an instance of the class Translator.

I also encountered AttributeError: 'NoneType' object has no attribute 'group' when running this code with googletrans-3.0.0, but it worked when I ran pip3 install googletrans==3.1.0a0.

I suggest double checking your version of googletrans. If in doubt, run pip list to confirm the version you have installed before running the above code.

Output:

Hola Mundo (es) --> Hello World (en)