Python实现翻译小工具【生长吧!Python】
【摘要】 利用Requests模块获取有道词典web页面的post信息,BeautifulSoup来获取需要的内容,通过tkinter模块生成gui界面。
一、背景
利用Requests模块获取有道词典web页面的post信息,BeautifulSoup来获取需要的内容,通过tkinter模块生成gui界面。
二、代码
fanyi.py代码如下:
#!/bin/env python
# -*- coding:utf-8 -*-
# _author:kaliarch
import requests
import urllib.parse
import time
import random
import hashlib
import json
class search(object):
def __init__(self):
self.url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
def getData(self,search_name):
# salt =i = "" + ((new Date).getTime() + parseInt(10 * Math.random(), 10)
salt = ((time.time() * 1000) + random.randint(1,10))
# sign = n.md5("fanyideskweb" + t + i + "ebSeFb%=XZ%T[KZ)c(sy!")
sign_text = "fanyideskweb" + search_name + str(salt) + "ebSeFb%=XZ%T[KZ)c(sy!"
sign = hashlib.md5((sign_text.encode('utf-8'))).hexdigest()
paydata = {
'i': search_name,
'from': 'AUTO',
'to': 'AUTO',
'smartresult': 'dict',
'client': 'fanyideskweb',
'salt': salt,
'sign': sign,
'doctype': 'json',
'version': '2.1',
'keyfrom': 'fanyi.web',
'action': 'FY_BY_CLICKBUTTION',
'typoResult': 'false'
}
return paydata
def getHeader(self):
header = {
'Host': 'fanyi.youdao.com',
'Referer': 'http://fanyi.youdao.com/',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',
'Cookie': 'OUTFOX_SEARCH_USER_ID=-846616837@1.80.219.201; OUTFOX_SEARCH_USER_ID_NCOO=129549097.60835753; UM_distinctid=15ff309f18ddc-094cb5494ad815-5d4e211f-1fa400-15ff309f18e449; _ga=GA1.2.184261795.1517119351; __guid=204659719.2556877880764680700.1518435624954.942; JSESSIONID=aaa3A5BLhtTrh4TPX_mgw; monitor_count=2; ___rl__test__cookies=1518488731567'
}
return header
def getRequest(self,paydata,header):
_data = urllib.parse.urlencode(paydata).encode('utf-8')
_header = header
response = requests.post(self.url,data=_data,headers=_header)
return response.text
def getResult(self,response):
result_text = json.loads(response)
#src = result_text['translateResult'][0][0]['src']
tgt = result_text['translateResult'][0][0]['tgt']
return tgt
def main(self,search_name):
app = search()
paydata = app.getData(search_name)
header = app.getHeader()
response = app.getRequest(paydata, header)
tgt = app.getResult(response)
return tgt
windows.py代码如下:
#!/bin/env python
# -*- coding:utf-8 -*-
# _author:kaliarch
import tkinter as tk
from fanyi import search
class application:
def __init__(self):
self.windows = tk.Tk()
self.windows.title("翻译小工具")
self.windows.geometry("280x350+700+300")
#提交按钮
self.submit_btn = tk.Button(self.windows, text="查询",command=self.submit)
self.submit_btn.place(x=220, y=10, width=50, height=25)
# 定义输入框
self.entry = tk.Entry(self.windows)
self.entry.place(x=10, y=10, width=200, height=40)
#输出内容
self.result_text = tk.Text(self.windows, background="#ccc")
self.result_text.place(x=10, y=90, width=260, height=245)
# 翻译结果标题
self.title_label = tk.Label(self.windows, text="翻译结果:")
self.title_label.place(x=10, y=65)
self.search_result = search()
def submit(self):
#1.获取用户输入
context = self.entry.get()
#2.利用有道翻译
result = self.search_result.main(context)
#3.输出
self.result_text.delete(1.0,tk.END)
self.result_text.insert(tk.END,result)
def run(self):
self.windows.mainloop()
if __name__ == '__main__':
winapp = application()
winapp.run()
setup.py代码如下:
# -*- coding:utf-8 -*-
# _author:kaliarch
import sys
from cx_Freeze import setup,Executable
import os
os.environ['TCL_LIBRARY'] = r"C:\Program Files\Python36\tcl\tcl8.6"
os.environ['TK_LIBRARY'] = r"C:\Program Files\Python36\tcl\tk8.6"
include_files = [
r"C:\Program Files\Python36\DLLs\tcl86t.dll",
r"C:\Program Files\Python36\DLLs\tk86t.dll",
]
build_exe_options = {
"packages":["os","tkinter","requests","idna"],
"include_files":include_files
}
base = None
if sys.platform == "win32":
base = "Win32GUI"
setup(name = "translate_tool",
version = "0.1",
description = "fanyitools!",
options = {"build_exe":build_exe_options},
executables = {Executable("windows.py",base=base,icon='img.ico')}
)
三、效果展示
运行windows.py,输入想要翻译的内容,点击翻译即可查看翻译结果
可以利用cx_Freeze打包成windows的mis安装小程序,方便使用
切换到项目目录下执行python setup.py bdist_msi
待执行完毕,可以项目文件下生成两个文件夹dist中为msi安装文件,在其他windows服务器安装后就为build下的文件内容,在build下的exe.win-amd64-3.6下的windows.exe 就可打开小工具
进行安装测试
安装完成后可以运行安装目录下的windows.exe打开小工具
【生长吧!Python】有奖征文火热进行中:https://bbs.huaweicloud.com/blogs/278897
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)