Python 谷歌翻译, Python 语言翻译, Python免费无限语言翻译, How to Translate Languages in Python, Googletrans: Free and Unlimited Google translate API for Python, AttributeError: ‘NoneType’ object has no attribute ‘group’

Python 谷歌翻译, Python 语言翻译, How to Translate Languages in Python
Python 谷歌翻译, Python 语言翻译, How to Translate Languages in Python

 

Google 翻译是一项免费服务,可将单词、短语和整个网页翻译成100多种语言。您可能已经知道它,并且在您的生活中多次使用它。

在本教程中,您将学习如何使用Googletrans库在 Python 中执行语言翻译。Googletrans是一个免费且无限制的 Python 库,可对 Google Translate API进行非官方的Ajax调用,以检测语言并翻译文本。

 

以下是该库的主要功能:

  • 自动语言检测(它也提供语言检测)
  • 批量翻译
  • 快速可靠
  • HTTP/2 支持
  • 连接池

 

首先,让我们使用pip安装它:

pip3 install googletrans

 

翻译文本

 

导入必要的库:

from googletrans import Translator, constants
from pprint import pprint

 

Googletrans 为我们提供了一个方便的界面,让我们初始化我们的翻译器实例:

# init the Google API translator
translator = Translator()

 

请注意, Translator 类有几个可选参数:

  • service_urls: 这应该是一个字符串列表,这些字符串是 google translate API 的 URLs,一个例子是["translate.google.com", "translate.google.co.uk"].
  • user_agent:将包含在请求中的User-Agent标头中的字符串。
  • proxies(dictionary):一个 Python 字典,将协议或协议和主机映射到代理的 URL,一个例子是{'http': 'example.com:3128', 'http://domain.example': 'example.com:3555'},更多关于本教程中的代理。
  • timeout:您发出的每个请求的超时时间,以秒表示。

 

现在我们只需使用translate()方法来获取翻译文本:

# translate a spanish text to english text (by default)
translation = translator.translate("Hola Mundo")
print(f"{translation.origin} ({translation.src}) --> {translation.text} ({translation.dest})")

 

这将打印原始文本和语言以及翻译后的文本和语言:

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

 

如果上面的代码导致这样的错误:

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

 

然后您必须卸载当前的googletrans版本并使用以下命令安装新版本:

$ pip3 uninstall googletrans
$ pip3 install googletrans==3.1.0a0

 

回到代码,它会自动检测语言并默认翻译成英语,让我们翻译成另一种语言,例如阿拉伯语:

# translate a spanish text to arabic for instance
translation = translator.translate("Hola Mundo", dest="ar")
print(f"{translation.origin} ({translation.src}) --> {translation.text} ({translation.dest})")

 

"ar" 是阿拉伯语的语言代码,这里是输出:

Hola Mundo (es) --> مرحبا بالعالم (ar)

 

现在让我们设置源语言并翻译成英语:

# specify source language
translation = translator.translate("Wie gehts ?", src="de")
print(f"{translation.origin} ({translation.src}) --> {translation.text} ({translation.dest})")

 

输出:

Wie gehts ? (de) --> How are you ? (en)

 

您还可以检查其他翻译和其他一些额外数据:

# print all translations and other data
pprint(translation.extra_data)

 

查看输出:

{'all-translations': [['interjection',
                       ['How are you doing?', "What's up?"],
                       [['How are you doing?', ["Wie geht's?"]],
                        ["What's up?", ["Wie geht's?"]]],
                       "Wie geht's?",
                       9]],
 'confidence': 1.0,
 'definitions': None,
 'examples': None,
 'language': [['de'], None, [1.0], ['de']],
 'original-language': 'de',
 'possible-mistakes': None,
 'possible-translations': [['Wie gehts ?',
                            None,
                            [['How are you ?', 1000, True, False],
                             ["How's it going ?", 1000, True, False],
                             ['How are you?', 0, True, False]],
                            [[0, 11]],
                            'Wie gehts ?',
                            0,
                            0]],
 'see-also': None,
 'synonyms': None,
 'translation': [['How are you ?', 'Wie gehts ?', None, None, 1]]}

大量数据可以从中受益,您拥有所有可能的翻译、信心、定义甚至示例。

 

翻译短语列表

 

您还可以传递文本列表来单独翻译每个句子:

# translate more than a phrase
sentences = [
    "Hello everyone",
    "How are you ?",
    "Do you speak english ?",
    "Good bye!"
]
translations = translator.translate(sentences, dest="tr")
for translation in translations:
    print(f"{translation.origin} ({translation.src}) --> {translation.text} ({translation.dest})")

 

输出:

Hello everyone (en) --> herkese merhaba (tr)
How are you ? (en) --> Nasılsın ? (tr)
Do you speak english ? (en) --> İngilizce biliyor musunuz ? (tr)
Good bye! (en) --> Güle güle! (tr)

 

语言检测

 

Google Translate API 也为我们提供了语言检测调用:

# detect a language
detection = translator.detect("नमस्ते दुनिया")
print("Language code:", detection.lang)
print("Confidence:", detection.confidence)

 

这将打印检测到的语言的代码以及置信度(1.0表示100%置信度):

Language code: hi
Confidence: 1.0

 

这将返回语言代码,要获取完整的语言名称,您可以使用GoogletransLANGUAGES提供的字典:

print("Language:", constants.LANGUAGES[detection.lang])

 

输出:
Language: hindi

 

支持的语言

 

您可能知道,Google 翻译支持 100 多种语言,让我们打印所有语言:

# print all available languages
print("Total supported languages:", len(constants.LANGUAGES))
print("Languages:")
pprint(constants.LANGUAGES)

 

这是一个截断的输出:

Total supported languages: 107
{'af': 'afrikaans',
 'sq': 'albanian',
 'am': 'amharic',
 'ar': 'arabic',
 'hy': 'armenian',
...
<SNIPPED>
...
 'vi': 'vietnamese',
 'cy': 'welsh',
 'xh': 'xhosa',
 'yi': 'yiddish',
 'yo': 'yoruba',
 'zu': 'zulu'}

 

结论

有了它,这个库对于想要快速翻译应用程序中文本的每个人来说都非常有用。但是,如前所述,该库是非官方的,作者指出单个文本的最大字符长度为 15K。

它也不能保证库在任何时候都能正常工作,如果你想使用稳定的 API,你应该使用官方的谷歌翻译 API

 

如果5xx这个库出现HTTP错误,那么谷歌已经禁止了你的 IP 地址,这是因为经常使用这个库,谷歌翻译可能会阻止你的 IP 地址,你需要考虑通过将代理字典传递给类中的参数来使用代理,或使用所讨论的官方 API。proxiesTranslator()

此外,我编写了一个快速的 Python 脚本,它允许您在命令行中翻译句子和文档中的文本,请在此处查看

最后,我鼓励您进一步探索该库,查看其官方文档

本文:Python 谷歌翻译, Python 语言翻译, How to Translate Languages in Python

Loading

Add a Comment

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.