我正在按照此教程使用python googletrans将文本从西班牙语翻译成英语,但我收到此错误:
TypeError:Translator.translate() 缺少 1 个必需的位置参数:'text'
我使用googletrans 3.0.0和python 3.10.6
这是我的代码:
from googletrans import Translator, constants
translation = Translator.translate("Hola Mundo", dest="en")
print(f"{translation.origin} ({translation.src}) --> {translation.text} ({translation.dest})")
我已经尝试使用
Translator.translate(text="Hola Mundo", dest="en")
并且这个答案对我不起作用,我收到了这个错误:
AttributeError: 'NoneType' object has no attribute 'group'
我按照本教程中所述切换到googletrans==3.1.0a0,但错误仍然存在
任何帮助将不胜感激。 🙂
您链接到的答案是正确的,您的代码的问题如下所述:您直接从类调用该方法,而不是创建实例。
供将来参考,在 Python 中,类名通常以不带下划线的首字母大写形式编写(例如
Translator
、DataFrame
),而诸如类实例之类的变量则使用带下划线的小写字母(例如 translator
、num_entries
)。我们更常见(尽管并非总是)在类实例上调用类方法。
此示例的正确代码是:
from googletrans import Translator, constants
translator = Translator()
translation = translator.translate("Hola Mundo", dest="en")
print(f"{translation.origin} ({translation.src}) --> {translation.text} ({translation.dest})")
请注意,
translator
是类Translator
的实例。
我在用
AttributeError: 'NoneType' object has no attribute 'group'
运行这段代码时也遇到了googletrans-3.0.0
,但是当我运行pip3 install googletrans==3.1.0a0
时它起作用了。
我建议仔细检查您的 googletrans 版本。如果有疑问,请在运行上述代码之前运行
pip list
确认您安装的版本。
输出:
Hola Mundo (es) --> Hello World (en)