如何通过Google Cloud Translate获取译文的英文拼音发音?
获取Google Cloud Translate API的罗马化音译(拼音形式)方案
Google Cloud Translate API的v3版本支持返回目标语言的罗马化音译结果,你可以通过添加特定请求参数实现,无需额外付费库。
实现步骤
- 切换到v3版本API:v2版本不支持音译功能,需使用v3版本的客户端库。
- 配置音译参数:在翻译请求中加入
transliteration_config字段,指定目标语言对应的罗马化编码(比如印地语的罗马化编码为hi-Latn)。
Python示例代码
from google.cloud import translate_v3 as translate def get_translation_with_transliteration(text, project_id): client = translate.TranslationServiceClient() parent = f"projects/{project_id}/locations/global" response = client.translate_text( request={ "parent": parent, "contents": [text], "source_language_code": "en", "target_language_code": "hi", "transliteration_config": { "source_language_code": "hi", "target_language_code": "hi-Latn" } } ) for item in response.translations: print(f"翻译结果: {item.translated_text}") print(f"音译(拼音): {item.transliterated_text}") # 替换为你的Google Cloud项目ID get_translation_with_transliteration("Hello", "your-project-id")
关键说明
- 运行前安装客户端库:
pip install google-cloud-translate - 需在Google Cloud控制台启用Translate API,并配置好服务账号密钥
- 不同语言的罗马化编码可参考官方语言规范,比如中文拼音用
zh-Latn-pinyin,日语罗马音用ja-Latn
内容的提问来源于stack exchange,提问作者Varun A M
相关产品推荐
相关产品推荐

