image.png
有的地方需要修改
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# 機器翻譯2.0(niutrans) WebAPI 接口調(diào)用示例
# 運行前:請先填寫Appid肛宋、APIKey落萎、APISecret
# 運行方法:直接運行 main 即可
# 結(jié)果: 控制臺輸出結(jié)果信息
#
# 1.接口文檔(必看):https://www.xfyun.cn/doc/nlp/niutrans/API.html
# 2.錯誤碼鏈接:https://www.xfyun.cn/document/error-code (錯誤碼code為5位數(shù)字)
# 3.個性化翻譯術(shù)語自定義:
# 登陸開放平臺 https://www.xfyun.cn/
# 在控制臺--機器翻譯(niutrans)--自定義翻譯處
# 上傳自定義翻譯文件(打開上傳或更新窗口伶授,可下載示例文件)
#
import requests
import datetime
import hashlib
import base64
import hmac
import json
class get_result(object):
def __init__(self, host):
# 應(yīng)用ID(到控制臺獲劝拖)
self.APPID = APPID
# 接口APISercet(到控制臺機器翻譯服務(wù)頁面獲壤愦取)
self.Secret = APISecret
# 接口APIKey(到控制臺機器翻譯服務(wù)頁面獲取)
self.APIKey = APIKey
# 以下為POST請求
self.Host = host
self.RequestUri = "/v2/ots"
# 設(shè)置url
# print(host)
self.url = "https://" + host + self.RequestUri
self.HttpMethod = "POST"
self.Algorithm = "hmac-sha256"
self.HttpProto = "HTTP/1.1"
# 設(shè)置當(dāng)前時間
curTime_utc = datetime.datetime.utcnow()
self.Date = self.httpdate(curTime_utc)
# 設(shè)置業(yè)務(wù)參數(shù)
# 語種列表參數(shù)值請參照接口文檔:https://www.xfyun.cn/doc/nlp/niutrans/API.html
self.Text = text
self.BusinessArgs = {
"from": from_language,
"to": to_language,
}
def hashlib_256(self, res):
m = hashlib.sha256(bytes(res.encode(encoding='utf-8'))).digest()
result = "SHA-256=" + base64.b64encode(m).decode(encoding='utf-8')
return result
def httpdate(self, dt):
"""
Return a string representation of a date according to RFC 1123
(HTTP/1.1).
The supplied date must be in UTC.
"""
weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()]
month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"][dt.month - 1]
return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month,
dt.year, dt.hour, dt.minute, dt.second)
def generateSignature(self, digest):
signatureStr = "host: " + self.Host + "\n"
signatureStr += "date: " + self.Date + "\n"
signatureStr += self.HttpMethod + " " + self.RequestUri \
+ " " + self.HttpProto + "\n"
signatureStr += "digest: " + digest
signature = hmac.new(bytes(self.Secret.encode(encoding='utf-8')),
bytes(signatureStr.encode(encoding='utf-8')),
digestmod=hashlib.sha256).digest()
result = base64.b64encode(signature)
return result.decode(encoding='utf-8')
def init_header(self, data):
digest = self.hashlib_256(data)
# print(digest)
sign = self.generateSignature(digest)
authHeader = 'api_key="%s", algorithm="%s", ' \
'headers="host date request-line digest", ' \
'signature="%s"' \
% (self.APIKey, self.Algorithm, sign)
# print(authHeader)
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Method": "POST",
"Host": self.Host,
"Date": self.Date,
"Digest": digest,
"Authorization": authHeader
}
return headers
def get_body(self):
content = str(base64.b64encode(self.Text.encode('utf-8')), 'utf-8')
postdata = {
"common": {"app_id": self.APPID},
"business": self.BusinessArgs,
"data": {
"text": content,
}
}
body = json.dumps(postdata)
# print(body)
return body
def call_url(self):
if self.APPID == '' or self.APIKey == '' or self.Secret == '':
print('Appid 或APIKey 或APISecret 為空囚戚!請打開demo代碼氮唯,填寫相關(guān)信息。')
else:
code = 0
body = self.get_body()
headers = self.init_header(body)
# print(self.url)
response = requests.post(self.url, data=body, headers=headers, timeout=8)
status_code = response.status_code
# print(response.content)
if status_code != 200:
# 鑒權(quán)失敗
print("Http請求失敗良风,狀態(tài)碼:" + str(status_code) + "谊迄,錯誤信息:" + response.text)
print("請根據(jù)錯誤信息檢查代碼,接口文檔:https://www.xfyun.cn/doc/nlp/niutrans/API.html")
else:
# 鑒權(quán)成功
respData = json.loads(response.text)
print(respData)
# 以下僅用于調(diào)試
code = str(respData["code"])
if code != '0':
print("請前往https://www.xfyun.cn/document/error-code?code=" + code + "查詢解決辦法")
if __name__ == '__main__':
APPID = "628709bc"
APISecret = "NmVkYWUzODllMTg3YTJiNDQzZTI5ZGE1"
APIKey = "03bd6ecf8291dba22a08ac20f0d0e7b1"
text = "肥厚型心肌病(HCM)是一種遺傳性心肌病烟央,其特征是不對稱性左心室肥厚统诺,是青少年猝死的首要原因,病理機制尚不明確疑俭。"
from_language = 'cn'
to_language = 'en'
##示例: host="ntrans.xfyun.cn"域名形式
host = "ntrans.xfyun.cn"
# 初始化類
gClass = get_result(host)
gClass.call_url()
image.png
image.png
一定要購買相應(yīng)的功能才可以運行