目录

Python-本地翻译库-googletrans

Python 本地翻译库 googletrans

Python 本地翻译库(如 googletrans )。以下是一个简单的示例,使用 googletrans 库来实现中英文对照翻译。

步骤1:安装 googletrans

首先,你需要安装 googletrans 库。可以通过以下命令安装:

pip install googletrans==4.0.0-rc1

步骤2:编写Python代码

接下来,编写Python代码来实现中英文对照翻译。

from googletrans import Translator

# 初始化翻译器
translator = Translator()

# 示例文本(每行英文对应相应的中文)
texts = [
    "Hello, how are you?",
    "I am fine, thank you.",
    "What is your name?",
    "My name is John."
]

# 翻译并输出中英文对照
for text in texts:
    translation = translator.translate(text, src='en', dest='zh-cn')
    print(f"英文: {text}")
    print(f"中文: {translation.text}\n")

步骤3:运行代码

运行上述代码后,你将看到每行英文对应的中文翻译。

示例输出

英文: Hello, how are you?
中文: 你好,你好吗?

英文: I am fine, thank you.
中文: 我很好,谢谢。

英文: What is your name?
中文: 你叫什么名字?

英文: My name is John.
中文: 我的名字是约翰。

注意事项

  1. API限制googletrans 库依赖于Google Translate的免费API,可能会有速率限制或不稳定的情况。如果需要更高的稳定性和速率,可以考虑使用Google Cloud Translation API(付费)。
  2. 网络连接googletrans 需要网络连接来访问Google Translate服务。
  3. 错误处理 :在实际应用中,建议添加错误处理机制,以应对网络问题或API限制。