初学瞎写的一个即时翻译,调用的必应翻译接口
初学写的一个调用翻译,这样在变量命名时不用打开翻译软件和去百度一下,直接就在编辑器里执行一下,还是挺方便的,闲来无事,故分享一下,看看大家有没有用得着的。。import requests
import re
import json
def trans(word):
flg=re.search(r'[\u4e00-\u9f5a]',word)
#en-GB 英文
#zh-Hans 中文,
from_word,to_word =('zh-Hans','en-GB') if flg else ('en-GB','zh-Hans')
uri = 'https://cn.bing.com/translator'
gi = requests.get(uri).text
ig = re.search(r'IG:"(.*?)"', gi).group(1)
token = re.search(r'params_AbusePreventionHelper = (.*?);', gi).group(1)
tokens = token.replace("[", "")
js = tokens.split(',')
t = js
url = 'https://cn.bing.com/ttranslatev3?isVertical=1&&IG={}&IID=translator.5027'.format(ig)
data = {
'fromLang': from_word,
'text': word,
'to': to_word,
'token': t,
'key': js,
'tryFetchingGenderDebiasedTranslations': 'true'
}
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'
}
try:
response = requests.post(url, data=data, headers=headers)
translations = response.json()['translations']
translated_text = translations['text']
return translated_text
except:
return "翻译失败"
if __name__ == '__main__':
word="你说你,想要逃,剩下空心要不要"
result=trans(word)
print(result)
#示例结果:You said that you want to escape, and you want to leave the hollow or not 感谢分享,正好拿去翻译PDF文件
谢谢楼主的分享 感谢分享 感谢分享。 感谢分享,学习学习 很好用!https://s21.ax1x.com/2024/11/13/pAgi0vn.png 后来无意中发现另外一个更简洁,调用的有道。。
import requests
from lxml import etree
def func(word):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'
}
url='https://m.youdao.com/translate'
data={
'inputtext': word,
'type': 'AUTO'}
resp=requests.post(url=url,headers=headers,data=data)
tree=etree.HTML(resp.text)
sr=tree.xpath('//ul[@id="translateResult"]/li/text()')
print(sr)
if __name__ == '__main__':
func('你好') 翻译引擎免费的不好用,好用的要么收费要么折腾 感谢分享
页:
[1]
2