Python制作翻译工具(程序员必备中英文翻译工具)

Posted 玩家_名狱

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python制作翻译工具(程序员必备中英文翻译工具)相关的知识,希望对你有一定的参考价值。

因为我英文不好,对接口、函数、结构体起名字的时候特别为难,因此我使用Python写了一个工具
在输入框输入中文,就可以生成Golang语言对应的接口、函数或接口体的写法;也可以切换到英文翻译。如下演示:

在这里插入图片描述

看懂代码之后,就可以修改为其它语言对应的写法。这里使用到百度的翻译API,因此自己要替换掉下面的两个key值就直接可以用了。
Baidufanyi类用于中英文翻译;
Initface类用于创建窗口,之后调用第一个Frame,这里为了能切换不同页面,使用两个Frame作为两个页面
OneFace类是第一个页面,init函数用于初始化页面,faceUI方法用于显示控件和逻辑控制,并使用了grid布局,oneBack方法用于销毁本页面并切换到另一个页面
TwoFace类和第一个页面用法一致,页面使用了pack布局

# 翻译.py
import tkinter
import requests
import hashlib
import pyperclip
import time


class Baidufanyi:
    def __init__(self, appid="百度API的应用ID", key="百度API的key"):
        self.appid = appid
        self.key = key
        self.salt = "1435660288"

    def getEnglish(self, srcdata):
        q = srcdata
        froms = "&from=zh"
        tos = "&to=en"
        sign = self.appid+q+self.salt+self.key
        sign = "&sign="+hashlib.md5(sign.encode(encoding='utf-8')).hexdigest()
        url = "http://api.fanyi.baidu.com/api/trans/vip/translate?"+"q="+q + \\
            froms+tos+"&appid="+self.appid+"&salt="+self.salt+sign
        result = requests.get(url)
        en_resu = eval(result.text)
        return en_resu["trans_result"][0]["dst"]

    def getChina(self, srcdata):
        q = srcdata
        froms = "&from=en"
        tos = "&to=zh"
        sign = self.appid+q+self.salt+self.key
        sign = "&sign="+hashlib.md5(sign.encode(encoding='utf-8')).hexdigest()
        url = "http://api.fanyi.baidu.com/api/trans/vip/translate?"+"q="+q + \\
            froms+tos+"&appid="+self.appid+"&salt="+self.salt+sign
        result = requests.get(url)
        en_resu = eval(result.text)
        return en_resu["trans_result"][0]["dst"]


fanyi = Baidufanyi()


class Initface:
    def __init__(self, windows):
        self.windows = windows
        self.windows.title("Golang翻译")
        self.windows.iconbitmap('D:/Python代码/Python的py转exe/mingyu.ico')
        self.windows.geometry('610x300')  # 设置窗口大小
        self.windows.configure(background='#87CEFF')
        OneFace(self.windows)  # 默认打开第一个页面


# 第一个页面
class OneFace:
    def __init__(self, oneWindows):
        self.oneWindows = oneWindows
        self.oneface = tkinter.Frame(self.oneWindows)
        self.oneface.configure(background='#87CEFF')
        self.oneface.grid()
        self.faceUI()

	# 使用了grid布局,显示控件,里面的函数用于逻辑处理
    def faceUI(self):
        # 获取翻译结果并写入到大文本框
        def getEn():
            text.delete("0.0", "end")  # 删除大文本框的内容
            srcdata = getTextInput(text_0).replace(
                '\\n', '').replace(' ', '')
            if srcdata == "":
                return
            data = fanyi.getEnglish(srcdata)
            text.insert("0.0", data)

        # 获取翻译结果并写入到大文本框
        def getInterface():
            text.delete("0.0", "end")  # 删除大文本框的内容
            srcdata = getTextInput(text_1).replace(
                '\\n', '').replace(' ', '')
            if srcdata == "":
                return
            data = fanyi.getEnglish(srcdata).replace(
                ' ', '').replace('?', '').replace('\\'', '')
            data = "// " + srcdata + "接口\\ntype " + \\
                data + "er" + " interface{\\n\\t\\n}"
            text.insert("0.0", data)

        # 获取翻译结果并写入到大文本框

        def getStruct():
            text.delete("0.0", "end")  # 删除大文本框的内容
            srcdata = getTextInput(text_2).replace(
                '\\n', '').replace(' ', '')
            if srcdata == "":
                return
            data = fanyi.getEnglish(srcdata).replace(
                ' ', '').replace('\\'', '').replace('?', '')
            data = "// " + srcdata + "结构体\\ntype " + \\
                data.capitalize() + " struct{\\n\\t\\n}"
            text.insert("0.0", data)

        # 获取翻译结果并写入到大文本框

        def getFunc():
            text.delete("0.0", "end")  # 删除大文本框的内容
            srcdata = getTextInput(text_3).replace(
                '\\n', '').replace(' ', '')
            if srcdata == "":
                return
            data = fanyi.getEnglish(srcdata).replace(
                ' ', '').replace('?', '').replace('\\'', '')
            data = "// " + srcdata + "函数\\nfunc " + \\
                data.capitalize() + "(  ) (err error) " + "{\\n\\t\\n}"
            text.insert("0.0", data)

        def CopyData():
            pyperclip.copy(text.get("0.0", "end"))
            nowtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            tishistr.set('已复制\\n' + nowtime)

        # 根据多行文本的变量名获取里面的值,textname:多行文本的变量名
        def getTextInput(textname):
            return textname.get("1.0", "end")

        oneBtn_1 = tkinter.Button(
            self.oneface, text="切换到中文翻译", bg="#32CD32", command=self.oneBack)
        oneBtn_1.grid(row="0", column="2")

        china0 = tkinter.Label(
            self.oneface, text="输入中文普通翻译:", bg='#87CEFF', font=("微软雅黑", 13))
        china0.grid(row="1", column="1")
        text_0 = tkinter.Text(self.oneface, width="30",
                              height="2", bg='#FFBBFF')
        text_0.grid(row="1", column="2")
        btn_0 = tkinter.Button(
            self.oneface, text="点击翻译", command=getEn, bg="#696969")
        btn_0.grid(row="1", column="3")

        china1 = tkinter.Label(
            self.oneface, text="输入中文获取接口:", bg='#87CEFF', font=("微软雅黑", 13))
        china1.grid(row="2", column="1")
        text_1 = tkinter.Text(self.oneface, width="30",
                              height="2", bg='#FFBBFF')
        text_1.grid(row="2", column="2")
        btn_1 = tkinter.Button(
            self.oneface, text="点击翻译", command=getInterface, bg="#696969")
        btn_1.grid(row="2", column="3")

        china2 = tkinter.Label(
            self.oneface, text="输入中文获取结构体:", bg='#87CEFF', font=("微软雅黑", 13))
        china2.grid(row="3", column="1")
        text_2 = tkinter.Text(self.oneface, width="30",
                              height="2", bg='#FFBBFF')
        text_2.grid(row="3", column="2")
        btn_2 = tkinter.Button(
            self.oneface, text="点击翻译", command=getStruct, bg="#B4EEB4")
        btn_2.grid(row="3", column="3")

        china3 = tkinter.Label(
            self.oneface, text="输入中文获取函数:", bg='#87CEFF', font=("微软雅黑", 13))
        china3.grid(row="4", column="1")
        text_3 = tkinter.Text(self.oneface, width="30",
                              height="2", bg='#FFBBFF')
        text_3.grid(row="4", column="2")
        btn_3 = tkinter.Button(
            self.oneface, text="点击翻译", command=getFunc, bg="#AB82FF")
        btn_3.grid(row="4", column="3")

        # 多行文本输入框
        tishistr = tkinter.StringVar()
        tishi = tkinter.Label(
            self.oneface, textvariable=tishistr, bg='#87CEFF', font=("微软雅黑", 10))
        tishi.grid(row="5", column="1")
        text = tkinter.Text(self.oneface, width="40",
                            height=8, bg='#FF83FA')
        text.grid(row="5", column="2")
        btn_4 = tkinter.Button(
            self.oneface, text="复制译文", command=CopyData, bg="#FF6A6A")
        btn_4.grid(row="5", column="3")

    def oneBack(self):
        self.oneface.destroy()
        TwoFace(self.oneWindows)


# 第二个页面
class TwoFace():
    def __init__(self, twoWindows):
        self.twoWindows = twoWindows
        self.twoface = tkinter.Frame(self.twoWindows)
        self.twoface.config(bg='#87CEFF')
        self.twoface.pack()
        self.faceUI()

	# 使用了pack布局,显示控件
    def faceUI(self):
        # 根据多行文本的变量名获取里面的值,textname:多行文本的变量名
        def getTextInput(textname):
            return textname.get("1.0", "end")

        def getCh():
            twoText_2.delete("0.0", "end")  # 删除大文本框的内容
            srcdata = getTextInput(twoText_0).replace(
                '\\n', '').replace(' ', '')
            if srcdata == "":
                return
            data = fanyi.getChina(srcdata)
            twoText_2.insert("0.0", data)

        twoBtn_1 = tkinter.Button(
            self.twoface, text="切换到英文翻译", bg="#32CD32", command=self.twoBack)
        twoBtn_1.pack()
        twoText_0 = tkinter.Text(
            self.twoface, width="50", height="8", bg='#FF83FA')
        twoText_0.pack()
        twoBtn_0 = tkinter.Button(
            self.twoface, text="点击翻译", bg="#7B68EE", command=getCh)
        twoBtn_0.pack()
        twoText_2 = tkinter.Text(
            self.twoface, width="70", height="8", bg='#FF83FA')
        twoText_2.pack()

	# 切换到其他页面
    def twoBack(self):
        self.twoface.destroy()  # 销毁页面
        OneFace(self.twoWindows)  # 切换到另一个页面


if __name__ == '__main__':
    windows = tkinter.Tk()
    Initface(windows)
    windows.mainloop()

然后使用命令打包

 pyinstaller -F -w -i D:\\Python代码\\Python的py转exe\\mingyu.ico D:\\Python代码\\Python的py转exe\\翻译.py

得到一个exe的文件
在这里插入图片描述

以上是关于Python制作翻译工具(程序员必备中英文翻译工具)的主要内容,如果未能解决你的问题,请参考以下文章

Python 打造基于有道翻译的命令行翻译工具(命令行爱好者必备)

Python爬虫实战之制作桌面翻译工具

python制作英语翻译小工具

Python爬虫实战,破解有道翻译JS加密,制作桌面翻译工具更新版

Python爬虫实战,破解百度翻译JS加密,制作桌面翻译工具

qt中制作添加 .ts 翻译文件