发布时间:2025-12-09 12:04:38 浏览次数:1
使用Google翻译Api
pip install --upgrade google-cloud-translate要运行客户端库,必须首先创建服务帐户并设置环境变量来设置身份验证。
将环境变量GOOGLE_APPLICATION_CREDENTIALS设置为包含服务帐户密钥的JSON文件的文件路径。在Linux或macOS系统中设置方法如下:
pip install --upgrade google-cloud-translate代码如下:
# Imports the Google Cloud client libraryfrom google.cloud import translate# Instantiates a clienttranslate_client = translate.Client()# The text to translatetext = u'Hello, world!'# The target languagetarget = 'ru'# Translates some text into Russiantranslation = translate_client.translate( text, target_language=target)print(u'Text: {}'.format(text))print(u'Translation: {}'.format(translation['translatedText']))要想将文件中的国家名称批量翻译并输出,可以写出下面这样的代码:
#!/usr/bin/env python#encoding: utf-8# Imports the Google Cloud client libraryfrom google.cloud import translate# Instantiates a clienttranslate_client = translate.Client()# The target languagetarget = 'en'd = {}with open('world_country_code.csv', 'r') as fpr: for line in fpr.readlines(): country = line.strip() if country.endswith(':'): result_line = country elif country is '': result_line = country else: # Translates some text into Russian translation = translate_client.translate(country, target_language=target) result_line = translation['translatedText'] result_line = '{},{}'.format(country, result_line) print result_line参考:
https://cloud.google.com/translate/docs/reference/libraries#client-libraries-usage-python