当前位置:网站首页>70 lines of code, a desktop automatic translation artifact
70 lines of code, a desktop automatic translation artifact
2022-07-30 15:46:00 【Programmer Wolfberry.】
At work, it is often necessary to communicate with foreign friends by email,Naihe work computer does not have translation software such as Youdao Dictionary installed,Combine with your needs,Create your own desktop translation artifact.
基本思路:基于PySimpleGUI开发桌面GUI→获取键盘输入→Access Google TranslateAPI→The crawler gets the translation result(Which involves regular expression matching translation results)→输出翻译结果→翻译完成.
PySimpleGUI是什么?
创建图形用户界面 (GUI)可能很困难, 有许多不同的Python GUI工具包可供选择.The top three most frequently mentioned are Tkinter, wxPython 和 PyQt (或PySide2). 但是PySimpleGUInewer toolkit,Its purpose is to make createGUI更加容易.
PySimpleGUI The main role is to becomeTkinter, wxPython和PyQt之上的抽象层.You can think of it as a wrapper, Get closer to the designerGUI 的距离. 虽然建立GUI 变的很简单, Relatively many details are ignored, That means you can only pressPySimpleGUI provided functions to use.This version is erected on Tkinter 之上, Of course there are other versions, 像是PySimpleGUIQt, PySimpleGUIWx, PySimpleGUIWeb, …
So what are the advantages, 就是简单, The disadvantage is also simple, The following describes how to use it, 其他的 GUI It's hard to say a lot in just one article.
使用步骤
引入库
代码如下(示例):
import reimport htmlfrom urllib import parseimport requestsimport PySimpleGUI as sg构建爬虫url
代码如下(示例):
url = 'http://translate.google.cn/m?q=%s&tl=%s&sl=%s'该处使用的url网络请求的数据,这里用到了%字符串格式化方法.Three parameters are required:text——需要翻译的内容, to_language——目标语言类型, text_language——当前语言类型.
Build the translation function
代码如下(示例):
def translate(text, to_language="en", text_language="auto"): text = parse.quote(text) url1 = url % (text, to_language, text_language) response = requests.get(url1) data = response.text # print(data) expr = r'(?s)class="(?:t0|result-container)">(.*?)<' result = re.findall(expr, data) print(result) if (len(result) == 0): return "" return html.unescape(result[0])printStatements are used for upfront debugging,You can comment out after debugging is successful,也可以忽略,不影响使用!
GUI搭建
代码如下(示例):
sg.theme('bluepurple') # 设置主题font = ("fangsong",12) # 字体仿宋,大小12menu = [["Help",["About","Item","Author"]]] # 菜单栏设置value = ['汉语','英语','日语','法语','俄语','自动'] # 语言选择(前端显示),默认只有6种,可以自己添加var = ['zh','en','ja','fr','ru','auto'] # 语言选择(When the backend executes)dic = dict(zip(value,var)) # Language dictionary configurationlayout = [[sg.Menu(menu, tearoff=False)], [sg.Text(text='Input',size=(26,1)), sg.Text(text='将',size=(2,1),justification='center'), sg.Combo(values=value, key='from', size=(10,1)), sg.Text(text='翻译为',size=(5,1),justification='center'), sg.Combo(values=value, key='to', size=(10,1))], [sg.Multiline(key="-IN-",size=(60, 8),font=font)], [sg.Text(text='Output',size=(30,1))], [sg.Multiline(key="-OUT-",size=(60, 8),font=font)], [sg.Text(text='',size=(36,1)), sg.Button("翻译", size=(6,1)), sg.Button("清除", size=(6,1)), sg.Button("退出", size=(6,1))] ]window = sg.Window("Homemade desktop translator", layout, icon="CT.ico") # 设置窗口名称,窗口布局,以及图标layout为GUI布局,Use list mode,Arranged according to rows and columns.
Logical execution statement
代码如下(示例):
while True: event, values =window.read() if event in (None, "退出"): # 点击“X”或者“退出”button to exit break if event == "翻译": if values["to"]=='' or values["from"]=='': # Pop-up prompt when no language type is selected sg.Popup("Please select a language type and try again,谢谢!") else: tar = translate(values["-IN-"],dic[values["to"]],dic[values["from"]]) window["-OUT-"].Update(tar) if event =="清除": window["-IN-"].Update("") window["-OUT-"].Update("") if event == "About": sg.Popup("使用方法:", "'翻译'确认输入,and output the translation result", "'清除'Clear existing input,Clear the translated result", "'退出'取消,并退出App", title='', font = font, auto_close = 1) if event == "Item": sg.Popup("Translation type:", "'输入类型' Type of language entered", "'输出类型' 输出的语言类型", title = '', font = font, auto_close = 1) if event == "Author": sg.Popup("作者简介:", "姓名:XXXXXX", "Wechat:XXXXXX", "E-mail:[email protected]", title = '', font = font, auto_close = 1)window.close()windows.read()Can be understood as monitoring,分别有事件event,返回值values.
while循环,When the event is empty or is“退出”是=时,结束循环,并退出.
PopupPop-up window for message prompts,can be used as a warning,提示,Re-confirmation interface.
界面效果

总结
到这里,The entire project has been completed,Some basic skills involved,A little more power is needed,好了,今天的分享就到这里,How to use it will be updated laterpyinstallerFor packaging and distribution use.
【python学习】
学Python的伙伴,欢迎加入新的交流【君羊】:1020465983
一起探讨编程知识,成为大神,群里还有软件安装包,实战案例、学习资料
边栏推荐
猜你喜欢

Delayed message queue

2022最新 | 室外单目深度估计研究综述

Mysql数据库查询好慢,除了索引,还能因为什么?

Sparse-PointNet: See Further in Autonomous Vehicles 论文笔记

Flask入门学习教程

经典实例分割模型Mask RCNN原理与测试

In-depth analysis of Kubernetes application management

GeoServer + openlayers

golang modules initialization project

后浪来袭!阿里产出“第二代”容器技术手册及脑图,这也太香了吧
随机推荐
GeoServer + openlayers
视频加密的误解
Configuration - Notes
编译、链接 - 笔记 - 3
【云原生】阿里云ARMS业务实时监控
TiDB tool download
TensorFlow custom training function
Example of video switching playback (video switching example) code
延时消息队列
How do luxury giants such as GUCCI and LV deploy the metaverse, should other brands keep up?
B+树索引页大小是如何确定的?
RobotStudio实现喷漆、打磨等功能(曲面路径生成与仿真)
TiDB 工具功能概览
tiup list
GeoServer
timed task corn
【喂到嘴边了的模块】准备徒手撸GUI?用Arm-2D三分钟就够了
类和对象(下篇)
组态 - 笔记
Introduction to kasini3000