初学写的一个调用翻译,这样在变量命名时不用打开翻译软件和去百度一下,直接就在编辑器里执行一下,还是挺方便的,闲来无事,故分享一下,看看大家有没有用得着的。。
[Python] 纯文本查看 复制代码 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[1][1:33]
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[0],
'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()[0]['translations']
translated_text = translations[0]['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 |