python 在线翻译_实现的英语翻译

python 在线翻译_实现的英语翻译百度翻译开放平台APITencentAI开放平台的翻译APIYoudao翻译APIDeepL翻译APITranslator是一种成熟的、可定制和可扩展的机器翻译技术

1、简介

一些在线免费的英语翻译开发接口有:

  • Google Translate API
  • Microsoft Translator API
  • 百度翻译开放平台 API
  • Tencent AI 开放平台的翻译 API
  • Youdao 翻译 API
  • Yandex.Translate API
  • DeepL 翻译 API

2、在线翻译接口

2.1 Google Translate API

http://translate.google.cn/translate_a/single?client=gtx&dt=t&dj=1&ie=UTF-8&sl=auto&tl=zh_TW&q=calculate
import requests
url = 'http://translate.google.cn/translate_a/single?'
param = 'client=at&sl=en&tl=zh-CN&dt=t&q=google'
# from urllib.parse import urlencode
# param = urlencode(param)
r = requests.get(url+param)
print(r.status_code)

2.2 Microsoft Translator API

2.2.1 开发简介

Translator 是一种成熟的、可定制和可扩展的机器翻译技术。Translator 技术为整个 Microsoft 产品的翻译功能提供了动力,包括 Microsoft Translator 应用 安卓和iOS系统,微软 办公室, Edge, Sharepoint, Yammer, Visualstudio, 必应,以及 Skype.简单地将翻译集成到Web、桌面或移动应用程序中,使用行业标准的REST技术,Translator为任何开发者提供了丰富的功能集。 了解更多关于机器翻译的信息以及Translator的工作原理.
在这里插入图片描述

主要 API 功能:

  • 本机神经- 使用现代的神经机器翻译 (NMT) 作为默认的所有 支持的语言翻译语音和文字.NMT 技术改造了机器翻译, 为现有行业标准的统计机器翻译 (SMT) 技术提供了翻译质量方面的重大进展。在翻译之前, NMT 更好地捕捉完整句子的上下文, 提供更高质量的翻译和更多的人听的输出。了解更多关于 NMT 如何工作.

  • 一次翻译成多种语言– 只需向Translator云服务提出一个请求,就可以翻译成多种语言。翻译功能可以自动检测到源内容的语言。

  • 检测 自动检测发送到 API 的文本的语言, 以帮助决定哪些内容应发送到翻译。

  • 音译 将单词和句子从一个脚本转换为另一个脚本。例如, 您可以在拉丁字母 (拼音) 中显示汉字, 这样就可以由非中文读者阅读。

  • 双语词典- 显示从或到英文的替代翻译, 上下文中的单词示例, 以帮助您选择完美的翻译, 甚至使用这个词的翻译句子的例子。
    在这里插入图片描述

2.2.2 开发费用

翻译器服务是一种基于云的神经机器翻译服务,是 Azure 认知服务系列 REST API 的一部分,可用于任何操作系统。翻译器为全球数千家企业使用的许多 Microsoft 产品和服务提供支持,以执行语言翻译和其他与语言相关的操作。在本概述中,您将了解 Translator 如何使您能够跨所有受支持的语言为您的应用程序构建智能的多语言解决方案。

免费试用翻译服务:

  • 首先,您需要一个微软帐户;如果没有,可以在 Microsoft 帐户门户上免费注册。选择“创建 Microsoft 帐户”,然后按照步骤创建和验证新帐户。

  • 接下来,你需要有一个 Azure 帐户 – 导航到 Azure 注册页,选择“免费开始”按钮,然后使用 Microsoft 帐户凭据创建新的 Azure 帐户。
    在这里插入图片描述
    在这里插入图片描述

2.2.3 开发API

  • 翻译单个输入
curl -X POST "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from=en&to=zh-Hans" -H "Ocp-Apim-Subscription-Key: <client-secret>" -H "Content-Type: application/json; charset=UTF-8" -d "[{'Text':'Hello, what is your name?'}]"
  • 使用语言自动检测翻译单个输入
curl -X POST "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=zh-Hans" -H "Ocp-Apim-Subscription-Key: <client-secret>" -H "Content-Type: application/json; charset=UTF-8" -d "[{'Text':'Hello, what is your name?'}]"
  • 使用音译翻译
curl -X POST "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=zh-Hans&toScript=Latn" -H "Ocp-Apim-Subscription-Key: <client-secret>" -H "Content-Type: application/json; charset=UTF-8" -d "[{'Text':'Hello, what is your name?'}]"
  • 翻译多段文本
curl -X POST "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from=en&to=zh-Hans" -H "Ocp-Apim-Subscription-Key: <client-secret>" -H "Content-Type: application/json; charset=UTF-8" -d "[{'Text':'Hello, what is your name?'}, {'Text':'I am fine, thank you.'}]"
  • 翻译成多种语言
curl -X POST "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from=en&to=zh-Hans&to=de" -H "Ocp-Apim-Subscription-Key: <client-secret>" -H "Content-Type: application/json; charset=UTF-8" -d "[{'Text':'Hello, what is your name?'}]"
  • 构建您的 Python 应用程序
# https://cn.bing.com/translator?ref=TThis&from=zh-Hans&to=en&isTTRefreshQuery=1
# https://learn.microsoft.com/en-us/azure/cognitive-services/Translator/quickstart-translator-rest-api?tabs=csharp
# https://learn.microsoft.com/en-us/azure/cognitive-services/translator/translator-text-apis?tabs=python#translate-text
import requests, uuid, json

# Add your key and endpoint
key = "<your-translator-key>"
endpoint = "https://api.cognitive.microsofttranslator.com"

# location, also known as region.
# required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
location = "<YOUR-RESOURCE-LOCATION>"

path = '/translate'
constructed_url = endpoint + path

params = { 
   
    'api-version': '3.0',
    'from': 'en',
    'to': ['fr', 'zu']
}

headers = { 
   
    'Ocp-Apim-Subscription-Key': key,
    # location required if you're using a multi-service or regional (not global) resource.
    'Ocp-Apim-Subscription-Region': location,
    'Content-type': 'application/json',
    'X-ClientTraceId': str(uuid.uuid4())
}

# You can pass more than one object in body.
body = [{ 
   
    'text': 'I would really like to drive your car around the block a few times!'
}]

request = requests.post(constructed_url, params=params, headers=headers, json=body)
response = request.json()

print(json.dumps(response, sort_keys=True, ensure_ascii=False, indent=4, separators=(',', ': ')))

2.3 百度翻译开放平台 API

2.3.1 开发简介

https://fanyi-api.baidu.com/

  • 通用文本翻译API可为用户提供实时优质的多语言翻译服务,只需传入待翻译的内容,并指定要翻译的源语言(支持源语言语种自动检测)和目标语言,即可得到相应的翻译结果。
  • 现已支持200+语种互译,覆盖4万多个语言方向,可前往百度翻译官方网站体验。
  • 支持翻译结果同步至网盘保存,高级版/尊享版还支持自定义术语翻译功能。

在这里插入图片描述
通用翻译API支持提供200+语种互译的在线文本翻译服务,支持多达4万多个语言方向,且支持多语种自动检测。您只需调用通用翻译API,传入待翻译的内容,并指定要翻译的源语言(支持源语言语种自动检测)和目标语言,即可得到相应的翻译结果。任何第三方应用或网站都可以通过使用通用翻译API为用户提供实时优质的多语言翻译服务,提升产品体验。

2.3.2 开发费用

https://fanyi-api.baidu.com/doc/13

字符数以翻译的源语言字符长度为标准计算。空格、html标签等均计入字符。一个汉字,英文字母,标点符号等,均按照一个字符计费。
在这里插入图片描述
在这里插入图片描述

2.3.3 开发API

https://fanyi-api.baidu.com/api/trans/vip/translate

  • 请求方式: 可使用 GET 或 POST 方式,如使用 POST 方式,Content-Type 请指定为:application/x-www-form-urlencoded
  • 字符编码:统一采用 UTF-8 编码格式
  • query 长度:为保证翻译质量,请将单次请求长度控制在 6000 bytes以内(汉字约为输入参数 2000 个)
    在这里插入图片描述

如何在一次请求中翻译多个单词或者多段文本?
答:您可以在发送的字段 q 中用换行符(在多数编程语言中为转义符号 \n。其中 \n 是需要能被程序解析出来的换行符而不是字符串 \n),您可以用换行符来分隔要翻译的多个单词或者多段文本,这样您就能得到多段文本独立的翻译结果了。注意在发送请求之前需对 q 字段做 URL encode!

# -*- coding: utf-8 -*-

# This code shows an example of text translation from English to Simplified-Chinese.
# This code runs on Python 2.7.x and Python 3.x.
# You may install `requests` to run this code: pip install requests
# Please refer to `https://api.fanyi.baidu.com/doc/21` for complete api document

import requests
import random
import json
from hashlib import md5

# Set your own appid/appkey.
appid = 'INPUT_YOUR_APPID'
appkey = 'INPUT_YOUR_APPKEY'

# For list of language codes, please refer to `https://api.fanyi.baidu.com/doc/21`
from_lang = 'en'
to_lang =  'zh'

endpoint = 'http://api.fanyi.baidu.com'
path = '/api/trans/vip/translate'
url = endpoint + path

query = 'Hello World! This is 1st paragraph.\nThis is 2nd paragraph.'

# Generate salt and sign
def make_md5(s, encoding='utf-8'):
    return md5(s.encode(encoding)).hexdigest()

salt = random.randint(32768, 65536)
sign = make_md5(appid + query + str(salt) + appkey)

# Build request
headers = { 
   'Content-Type': 'application/x-www-form-urlencoded'}
payload = { 
   'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}

# Send request
r = requests.post(url, params=payload, headers=headers)
result = r.json()

# Show response
print(json.dumps(result, indent=4, ensure_ascii=False))

2.4 Tencent AI 开放平台的翻译 API

2.4.1 开发简介

https://cloud.tencent.com/document/api/551/17231

欢迎使用 机器翻译 API 3.0 版本。全新的 API 接口文档更加规范和全面,统一的参数风格和公共错误码,统一的 SDK/CLI 版本与 API 文档严格一致,给您带来简单快捷的使用体验。支持全地域就近接入让您更快连接腾讯云产品。

腾讯机器翻译(Tencent Machine Translation)结合了神经机器翻译和统计机器翻译的优点,从大规模双语语料库自动学习翻译知识,实现从源语言文本到目标语言文本的自动翻译,目前可支持中文与英文、日文、韩文三种语言的文本互译。

2.4.2 开发API

  • 输入示例
POST / HTTP/1.1
Host: tmt.tencentcloudapi.com
Content-Type: application/json
X-TC-Action: TextTranslate
<公共请求参数>

{ 
   
    "SourceText": "hello",
    "Source": "en",
    "Target": "zh",
    "ProjectId": 0
}
  • 输出示例
{ 
   
    "Response": { 
   
        "TargetText": "你好",
        "Source": "en",
        "Target": "zh",
        "RequestId": "000ee211-f19e-4a34-a214-e2bb1122d248"
    }
}

腾讯云 API 平台 是综合 API 文档、错误码、API Explorer 及 SDK 等资源的统一查询平台,方便您从同一入口查询及使用腾讯云提供的所有 API 服务。

import json

from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.common.abstract_client import AbstractClient
from tencentcloud.tmt.v import models


class TmtClient(AbstractClient):
    _apiVersion = '2018-03-21'
    _endpoint = 'tmt.tencentcloudapi.com'
    _service = 'tmt'
    
    def TextTranslate(self, request):
        """提供中文到英文、英文到中文的等多种语言的文本内容翻译服务, 经过大数据语料库、多种解码算法、翻译引擎深度优化,在新闻文章、生活口语等不同语言场景中都有深厚积累,翻译结果专业评价处于行业领先水平。<br /> 提示:对于一般开发者,我们建议优先使用SDK接入简化开发。SDK使用介绍请直接查看 5. 开发者资源 部分。 :param request: Request instance for TextTranslate. :type request: :class:`tencentcloud.tmt.v.models.TextTranslateRequest` :rtype: :class:`tencentcloud.tmt.v.models.TextTranslateResponse` """
        try:
            params = request._serialize()
            headers = request.headers
            body = self.call("TextTranslate", params, headers=headers)
            response = json.loads(body)
            model = models.TextTranslateResponse()
            model._deserialize(response["Response"])
            return model
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message)

2.5 Youdao 翻译 API

2.5.1 开发简介

https://fanyi.youdao.com/index.html#/
https://ai.youdao.com/?keyfrom=fanyi-new-nav#/
http://m.youdao.com/translate

基于有道神经网络翻译引擎的文本翻译服务,支持上百种语言的自动识别与互译,服务8亿用户,翻译质量业界领先。
在这里插入图片描述
文本翻译:将一段源语言文本转换成目标语言文本,可根据语言参数的不同实现多国语言之间的互译。
在这里插入图片描述

2.5.2 开发费用

  • 对于自然语言翻译服务,各接口拥有一定量的免费查询字符数(新用户注册账户时,系统会向您账户赠予50元体验资金),可免费体验有道智云的服务。
  • 先消费体验金额,体验金额耗尽后,才根据接口调用量在账户余额进行扣费。
  • 单次查询最大字符数默认为5000、每小时最大查询次数默认为100万。如无法满足您的需求,可联系我们,我们会评估您的需求,并做出适当调整。

在这里插入图片描述
在这里插入图片描述

2.5.3 开发API

文本翻译API接口提供有道的翻译服务,包含了中英翻译和小语种翻译功能。您只需要通过调用文本翻译API,传入待翻译的内容,并指定要翻译的源语言(支持源语言语种自动检测)和目标语言种类,就可以得到相应的翻译结果。

其中auto可以识别中文、英文、日文、韩文、法文、西班牙文、葡萄牙文、俄文、越南文、德文、阿拉伯文、印尼文、意大利文,其他语种无法识别,为提高准确率,请指定语种。

文本翻译API HTTPS地址:

https://openapi.youdao.com/api

在这里插入图片描述

import requests
from utils.AuthV3Util import addAuthParams

# 您的应用ID
APP_KEY = ''
# 您的应用密钥
APP_SECRET = ''

def createRequest():
    ''' note: 将下列变量替换为需要请求的参数 '''
    q = '待翻译文本'
    lang_from = '源语言语种'
    lang_to = '目标语言语种'
    vocab_id = '您的用户词表ID'

    data = { 
   'q': q, 'from': lang_from, 'to': lang_to, 'vocabId': vocab_id}

    addAuthParams(APP_KEY, APP_SECRET, data)

    header = { 
   'Content-Type': 'application/x-www-form-urlencoded'}
    res = doCall('https://openapi.youdao.com/api', header, data, 'post')
    print(str(res.content, 'utf-8'))


def doCall(url, header, params, method):
    if 'get' == method:
        return requests.get(url, params)
    elif 'post' == method:
        return requests.post(url, params, header)

# 网易有道智云翻译服务api调用demo
# api接口: https://openapi.youdao.com/api
if __name__ == '__main__':
    createRequest()

2.6 DeepL 翻译 API

https://www.deepl.com/zh/translator/l/en/zh

DeepL API为你提供对DeepL机器翻译技术的程序化访问,使你得以直接在你的网站上和应用程序中应用其高水准翻译能力。
DeepL在翻译质量方面一直优于竞争对手,其不仅体现于文本翻译。该API也支持.docx、.pptx、.txt、PDF和HTML文件翻译。

  • curl请求示例:
curl -X POST 'https://api-free.deepl.com/v2/translate' \
	-H 'Authorization: DeepL-Auth-Key [yourAuthKey]' \
	-d 'text=Hello%2C%20world!' \
	-d 'target_lang=DE'
  • http请求示例:
EXAMPLE REQUEST
POST /v2/translate HTTP/2
Host: api-free.deepl.com
Authorization: DeepL-Auth-Key [yourAuthKey]
User-Agent: YourApp/1.2.3
Content-Length: 37
Content-Type: application/x-www-form-urlencoded

text=Hello%2C%20world!&target_lang=DE
  • python请求示例:
import requests
def deepltrans(txt):
 url = "https://deepl-translator.p.rapidapi.com/translate"
    payload = { 
   
        "text": txt,
        "source": "en",
        "target": "zh"
    }
    headers = { 
   
        "content-type": "application/json",
        "X-RapidAPI-Key": "XXXX(这是你自己申请的api)",
        "X-RapidAPI-Host":"deepl-translator.p.rapidapi.com"
    }
    response = requests.request("POST", url, json=payload, headers=headers)
    trans=eval(response.text)
    return trans['text']
def get_text():
    with open("test.txt",'r',encoding="utf-8") as f:
        lines=[line.strip() for line in f.readlines()]
    return lines
def main():
    for i in get_text():
        print(deepltrans(i))
main()

2.7 Yandex.Translate API

https://translate.yandex.com/

它支持90多种语言,可以翻译单独的单词或完整的文本。该API可以为最终用户将Yandex.Translate嵌入到移动应用程序或Web服务中。或者翻译大量文本,例如技术文档。
在这里插入图片描述

  • JSON and JSONP interfaces
https://translate.yandex.net/api/v1.5/tr.json/translate
 ? [key=<API key>]
 & [text=<text to translate>]
 & [lang=<translation direction>]
 & [format=<text format>]
 & [options=<translation options>]
 & [callback=<callback function name>]

POST /api/v1.5/tr.json/translate?lang=en-ru&key=API-KEY HTTP/1.1
Host: translate.yandex.net
Accept: */*
Content-Length: 17
Content-Type: application/x-www-form-urlencoded

text=Hello World!
  • XML interface
https://translate.yandex.net/api/v1.5/tr/translate
 ? [key=<API key>]
 & [text=<text to translate>]
 & [lang=<translation direction>]
 & [format=<text format>]
 & [options=<translation options>]

2.8 其他

  • 爱词霸
    http://www.iciba.com/fy?a=fy
  • 海词
    https://corp.dict.cn/
  • 彩云小译
    https://fanyi.caiyunapp.com/#/

结语

如果您觉得该方法或代码有一点点用处,可以给作者点个赞,或打赏杯咖啡;╮( ̄▽ ̄)╭
如果您感觉方法或代码不咋地//(ㄒoㄒ)//,就在评论处留言,作者继续改进;o_O???
如果您需要相关功能的代码定制化开发,可以留言私信作者;(✿◡‿◡)
感谢各位大佬童鞋们的支持!( ´ ▽´ )ノ ( ´ ▽´)っ!!!

今天的文章python 在线翻译_实现的英语翻译分享到此就结束了,感谢您的阅读。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/81734.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注