6

Ptyhon如何免费调用Google翻译API

 2 years ago
source link: https://viencoding.com/article/136
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Ptyhon如何免费调用Google翻译API

改革春风吹满地,Google翻译不墙了。

众所周知,现在Google翻译在国内可以访问了,而且Google翻译要比百度之类的翻译优秀狠狠狠狠狠狠多,Google翻译是结合了自然语言处理与人工智能,所以翻译结果相对令人满意,不会出现太多的生硬的尴尬的翻译。今天我们讲一下Python调用Google翻译的方法。

这种其实大家都很难用到,因为吧,你在墙里面,它在墙外面(当然本站有办法让你嘿嘿嘿,请自己发现)。需要Google搜索Google Translate API,然后第一条就是。

  1. 首先要创建一个项目并使用这个项目(蓝色的按钮)快速链接:https://cloud.google.com/translate/docs/quickstart-client-libraries
  2. 项目创建后会给你一个json文件,用于api身份认证,这个json文件需要下载
  3. 配置环境变量 export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json" 后面的路径就是你下载的json文件路径,自己换掉。
  4. 安装Google Translate module:pip install --upgrade google-cloud-translate

这是一个使用DEMO:

# Imports the Google Cloud client library
from google.cloud import translate

# Instantiates a client
translate_client = translate.Client()

# The text to translate
text = u'Hello, world!'
# The target language
target = 'ru'

# Translates some text into Russian
translation = translate_client.translate(
    text,
    target_language=target)

print(u'Text: {}'.format(text))
print(u'Translation: {}'.format(translation['translatedText']))

安装谷歌翻译包

pip install googletrans
from googletrans import Translator
translator = Translator(service_urls=['translate.google.cn'])
source = 'I love you'
text = translator.translate(source,src='zh-cn',dest='en').text
print(text)

"我爱你"

OK,以上两种方法请自行选择,不过速度都不是很快,因为服务器可能有点远,.cn的域名访问也很慢。大家可以利用多线程或者协程减少IO等待时间。

viencoding.com版权所有,允许转载,但转载请注明出处和原文链接: https://viencoding.com/article/136
欢迎小伙伴们在下方评论区留言 ~ O(∩_∩)O
文章对我有帮助, 点此请博主吃包辣条 ~ O(∩_∩)O

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK