翻译小工具
from urllib import parseimport urllib
from win32com.client import Dispatch
import pythoncom
import hashlib
import urllib.parse
import random
import json
g_headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36'}
def getWinHttpReq(typeid, timeOut = 25):
pythoncom.CoInitialize()
WinHttpReq = Dispatch('WinHttp.WinHttpRequest.5.1')
WinHttpReq.SetTimeouts(8*10000, 8*10000, timeOut*10000, timeOut*10000)
if typeid == 2:
HTTPREQUEST_PROXYSETTING_PROXY = 2
WinHttpReq.SetProxy(HTTPREQUEST_PROXYSETTING_PROXY,"xxxxxx", "")
return WinHttpReq
winhttp = getWinHttpReq(1)
def SendWinHttpReq_2(WinHttpReq,sendUrl,reUrl=False,body=None,reType=1,headDic=None):
globalg_headers, g_headerss, GPcookie
WinHttpReq.SetOption(6, reUrl)# 设置是否跳转,False为重定向不自动跳转True为自动跳转
if body==None:# 设置/判断 请求类型 是GET 还是 post
WinHttpReq.Open('GET', sendUrl, False)
else:
WinHttpReq.Open('POST', sendUrl, False)
WinHttpReq.SetRequestHeader('User-Agent',g_headers['User-Agent']) #设置 浏览器 请求头
if headDic!=None:
for i in headDic:
try:
WinHttpReq.SetRequestHeader(i,headDic) # 设置头部信息
except:
continue
if body == None:
WinHttpReq.Send()
else:
if type(body) != type('11'):# 判断post数据类型是否为字符串类型
body = urllib.parse.urlencode(body) # 进行url编码
WinHttpReq.Send(body) # 发送
WinHttpReq.WaitForResponse() # 等待响应
if reType==1:
try:
objstr = WinHttpReq.ResponseBody.obj # get 服务器响应返回内容
except:
return ''
return objstr
if reType==2:
try:
return WinHttpReq.GetResponseHeader('Location')
except:
try:
objstr = WinHttpReq.ResponseBody.obj
except:
return ''
if objstr.startswith(b'\xef\xbb\xbf'):
objstr = objstr[3:]
return objstr.decode('utf-8','ignore')
return WinHttpReq.GetAllResponseHeaders()
def SendWinHttpReq(WinHttpReq, sendUrl, reUrl=False, body=None, reType=1, headDic=None, code='utf-8'):
global g_headers
WinHttpReq.SetOption(6, reUrl)
if body == None:
WinHttpReq.Open('GET', sendUrl, False)
else:
WinHttpReq.Open('POST', sendUrl, False)
WinHttpReq.SetRequestHeader('User-Agent', g_headers['User-Agent'])
if headDic != None:
for i in headDic:
try:
WinHttpReq.SetRequestHeader(i,headDic)
except:
continue
if body == None:
WinHttpReq.Send()
else:
if type(body) != type('11'):
body = parse.urlencode(body)
WinHttpReq.Send(body)
WinHttpReq.WaitForResponse()
if reType == 1:
try:
objstr = WinHttpReq.ResponseBody.obj
except:
return ''
if objstr.startswith(b'\xef\xbb\xbf'):
objstr = objstr[3:]
if code != None:
return objstr.decode(code,'ignore')
return objstr
if reType == 2:
try:
return WinHttpReq.GetResponseHeader('Location')
except:
try:
objstr = WinHttpReq.ResponseBody.obj
except:
return ''
if objstr.startswith(b'\xef\xbb\xbf'):
objstr = objstr[3:]
if code != None:
return objstr.decode(code, 'ignore')
return objstr
return WinHttpReq.GetAllResponseHeaders()
def strGetlen(strn, strx, strend):
sint = strn.find(strx)
strn = strnlen(strx):]
if strend == "":
return strn
eint = strn.find(strend)
return strn[:eint]
def getMD5(content):
encoding = 'utf-8'# 编码用utf-8
m2 = hashlib.md5()
m2.update(content.encode(encoding))
return m2.hexdigest()
def translate(text):
headData={'X-Requested-With': 'XMLHttpRequest',
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Referer': 'https://fanyi.youdao.com/',
'Cookie':'OUTFOX_SEARCH_USER_ID=1246911609@10.169.0.81; OUTFOX_SEARCH_USER_ID_NCOO=1980893172.0992112; UM_distinctid=17c7e122e12be-0fd8d04e99cb3a-b7a1438-1fa400-17c7e122e1310ed; P_INFO=18817122609|1634202753|1|youdao_zhiyun2018|00&99|null&null&null#hun&430100#10#0|&0||18817122609; JSESSIONID=aaa0_e_9U6Id95XIy8cYx; ___rl__test__cookies=1634284455005'
}
salt = str(random.random()*1000)
lts = str(random.random()*1000)
bv =getMD5(g_headers['User-Agent'])
sign =getMD5("fanyideskweb" + text + salt + "Y2FYu%TNSbMCxc3t2u^XT")
postUrl = 'https://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
postData='i='+urllib.parse.quote(text)+'&from=AUTO&to=AUTO&smartresult=dict&client=fanyideskweb&salt='+salt+'&sign='+sign+'<s='+lts+'&bv='+bv+'&doctype=json&version=2.1&keyfrom=fanyi.web&action=FY_BY_REALTlME'
authUrl= SendWinHttpReq(winhttp, postUrl, True, postData, 1, headData)
authUrl = json.loads(authUrl)
if authUrl['errorCode'] == 0:
try:
src=''
for cont in authUrl['translateResult'][0]:
src+=cont['tgt']
return src
except Exception as e:
print(e)
else:
return '翻译失败:'+str(authUrl['errorCode'])
if __name__ == '__main__':
text ='经过国家的不懈努力和华为的执着坚持,被加拿大无端拘押了三年的孟晚舟终于回家了。一直让人牵挂的巾帼英雄重获自由,让很多人喜极而泣。秀外慧中的孟晚舟以自己优雅的人格魅力和过人才气,在全世界面前为华为,也为中国做了一次免费的广告,这一次,华为、中国赢的漂亮。'
msg = translate(text)
print(msg)
看到有道友说百度翻译不了长字符.就发了一个,懒得打包.有道的翻译,Google也有.需要的再叫我.如有违规请直接删帖..感谢
import json
import requests
# 翻译函数,word 需要翻译的内容
def translate(word):
# 有道词典 api
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null'
# 传输的参数,其中 i 为需要翻译的内容
key = {
'type': "AUTO",
'i': word,
"doctype": "json",
"version": "2.1",
"keyfrom": "fanyi.web",
"ue": "UTF-8",
"action": "FY_BY_CLICKBUTTON",
"typoResult": "true"
}
# key 这个字典为发送给有道词典服务器的内容
response = requests.post(url, data=key)
# 判断服务器是否相应成功
if response.status_code == 200:
# 然后相应的结果
return response.text
else:
print("有道词典调用失败")
# 相应失败就返回空
return None
def get_reuslt(repsonse):
# 通过 json.loads 把返回的结果加载成 json 格式
result = json.loads(repsonse)
print ("输入的词为:%s" % result['translateResult']['src'])
print ("翻译结果为:%s" % result['translateResult']['tgt'])
def main():
print("本程序调用有道词典的API进行翻译,可达到以下效果:")
print("外文-->中文")
print("中文-->英文")
word = input('请输入你想要翻译的词或句:')
list_trans = translate(word)
get_reuslt(list_trans)
if __name__ == '__main__':
main() 你这个发的代码看起来有点累 建议发帖的时候点插入代码 这样插入的代码格式好看点。 支持原创 楼主厉害 学习了,感谢分享。 谢谢,真是需要的 认罪也算赢了吗,别看新闻只看片面嗷
宣传只持续一天。。。有点惨淡的说 厉害啊,谢谢高手的分享 大佬厉害!!,正在学习python 这个过一段时间,就没有用了吧?
页:
[1]
2