赞
踩
上一次,我们制作了火车站管理系统这一次,我们来做一个翻译工具,可以使用有道翻译的接口,可以为我们的代码编写便利许多,大家先安装这个图形化模块:PySimpleGUI,随后就可以开始编写了。
- #pip install PySimpleGUI
- #复制到cmd
- from urllib import request
- import urllib
- import re
- import PySimpleGUI as sg
- try:
- #翻译核心程序
- def fanyi(key):
- #-----伪装浏览器进行爬虫
- header={"User-Agent":" Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.54"}
- url="http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"
- #-----增加参数
- formdata={}
- formdata['i'] = key
- formdata['from'] = 'AUTO'
- formdata['to'] = 'AUTO'
- formdata['smartresult'] = 'dict'
- formdata['client'] = 'fanyideskweb'
- formdata['salt'] = '15821157689747'
- formdata['sign'] = 'd5a392995c28c285198043f7111d1d00'
- formdata['ts'] = '1582115768974'
- formdata['bv'] = 'ec579abcd509567b8d56407a80835950'
- formdata['doctype'] = 'json'
- formdata['version'] = '2.1'
- formdata['keyfrom'] = 'fanyi.web'
- formdata['action'] = 'FY_BY_CLICKBUTTION'
- data = urllib.parse.urlencode(formdata).encode('utf-8')
- #-----爬虫
- req=request.Request(url,data=data,headers=header)
- #-----解析
- resp=request.urlopen(req).read().decode()
- pat=r'"tgt":"(.*?)"}]]'
- result=re.findall(pat,resp)
-
- return result[0]
-
-
-
-
- #-----图形化界面设计
- layout = [[sg.T('欢迎来到翻译系统', key='-TXT-')],
- [sg.T('中文', key='-TXT-')],
- [sg.Input(key='-IN-', size=(20,1)),
- sg.B("翻译",key='-B-')
- ]]
-
-
- window = sg.Window('翻译系统', layout)
-
- while True:
- event, values = window.read()
-
- if event ==None:
- break
- elif event == '-B-':
- a=fanyi(values["-IN-"])
- sg.popup("英文是",a,title="翻译成功")
- window.close()
- except Exception as e:
- sg.popup("出现错误,错误码",e,title="出现错误")
-
- window.close()
好了,有道翻译python接口调用实战的项目就到这里,期待下一期项目吧!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。