修改Google翻译服务交互代码,返回翻译结果列表而非打印
Hey there! I've adjusted the Google Translate API sample code to meet your need—instead of printing translations directly, it will return a neat list of target language strings. Here's the modified version and a breakdown of the key changes:
Modified Code to Return Translation List
from __future__ import print_function from googleapiclient.discovery import build import argparse def translate_text_list(source_texts, source_lang, target_lang, api_key): """ Translates a list of source language strings to the target language Args: source_texts (list): List of strings to translate source_lang (str): Code for source language (e.g., 'en' for English) target_lang (str): Code for target language (e.g., 'es' for Spanish) api_key (str): Your Google Cloud API key Returns: list: Translated strings in the same order as source_texts """ service = build('translate', 'v2', developerKey=api_key) # Batch translate all texts in the input list result = service.translations().list( source=source_lang, target=target_lang, q=source_texts ).execute() # Extract translated texts from the API response and return as a list translated_list = [item['translatedText'] for item in result['translations']] return translated_list # Example usage to test the function if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--source_lang', required=True, help='Source language code') parser.add_argument('--target_lang', required=True, help='Target language code') parser.add_argument('--api_key', required=True, help='Google Cloud API key') args = parser.parse_args() # Sample source text list sample_texts = ["Hello world", "Python is great", "I love programming"] translations = translate_text_list(sample_texts, args.source_lang, args.target_lang, args.api_key) # Print result just for demonstration—you can use the returned list directly in your code print("Translations:", translations)
Key Changes Explained
- Wrapped the translation logic into a reusable function
translate_text_listthat accepts your source text list, language codes, and API key as parameters. - Replaced direct print statements with a list comprehension to extract
translatedTextvalues from the API response, collecting them into a structured list. - The function returns this list directly, so you can assign it to a variable and integrate it into your workflow easily.
- Added a clear docstring to explain the function's purpose, arguments, and return value for better readability and maintainability.
Important Notes
- Ensure you have the required dependency installed: run
pip install google-api-python-clientif you haven't already. - You'll need a valid Google Cloud API key with the Translate API enabled (set this up through the Google Cloud Console if you don't have one).
- Use ISO 639-1 language codes (e.g., 'fr' for French, 'zh-CN' for Simplified Chinese) for
source_langandtarget_lang.
内容的提问来源于stack exchange,提问作者user8270077




