from urllib import request
from urllib import parse
import json
import time
def translation(string):
url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) '
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36'}
data = {
'i': string,
'from': 'AUTO',
'to': 'AUTO',
'smartresult': 'dict',
'client': 'fanyideskweb',
'salt': '15805516827176',
'sign': '17cf93ee9a11894806209a83c480ca2b',
'ts': '1580551682717',
'bv': '334720d41a1d174718af3a3d58d56f23',
'doctype': 'json',
'version': '2.1',
'keyfrom': 'fanyi.web',
'action': 'FY_BY_CLICKBUTTION'}
data = parse.urlencode(data).encode("utf-8")
req = request.Request(url, data, headers)
response = request.urlopen(req)
html = response.read().decode("utf-8")
prasewords(html)
def prasewords(html):
trans = json.loads(html)
firstwords = trans['translateResult'][0][0]['src']
finaltrans = trans['translateResult'][0][0]['tgt']
output(firstwords, finaltrans)
def output(firstwords, finaltrans):
print("您输入的是:%s" % firstwords)
print("翻译结果是:%s" % finaltrans)
def main():
while True:
print("")
string = input("请输入要翻译的内容(输入quit或q或exit均可退出程序):")
if string == 'quit' or string == 'q' or string == 'exit':
break
translation(string)
time.sleep(3)
if __name__ == '__main__':
main()