目不识丁的我使用Python编写汉字注音小工具

一万点暴击伤害

人懒起来太可怕了,放了个十一充分激发了我的惰性。然后公众号就这么停了半个月,好惭愧…
新学期儿子的幼儿园上线了APP,每天作业通过app布置后,家长需要陪着孩子学习,并上传视频才算完成作业。来看看今天的课后作业吧:

看到最后的千字文,我就瞬间崩溃了,别说教孩子,我自己都一堆字不认识。老婆就是因为很多字需要手机查嫌麻烦,才把辅导孩子的任务甩给了我。平时我们中英文翻译的时候,经常使用百度翻译,那么今天我们使用Python来做一个自动注音的GUI工具吧!

Python的拼音模块

Python的模块库API,每次进去习惯第一动作,就是右键翻译为中文。可Python的拼音模块不需要这么做,因为涉及拼音等模块肯定和中文有关系,文档自然是中文的喽。
那么Python的拼音模块是什么? pypinyin

  • 特性

根据词组智能匹配最正确的拼音。
支持多音字。
简单的繁体支持, 注音支持。
支持多种不同拼音/注音风格。

  • 安装

pip install pypinyin

  • 使用示例
>>> from pypinyin import pinyin, lazy_pinyin, Style
>>> pinyin('中心')
[['zhōng'], ['xīn']]
>>> pinyin('中心', heteronym=True)  # 启用多音字模式
[['zhōng', 'zhòng'], ['xīn']]
>>> pinyin('中心', style=Style.FIRST_LETTER)  # 设置拼音风格
[['z'], ['x']]
>>> pinyin('中心', style=Style.TONE2, heteronym=True)
[['zho1ng', 'zho4ng'], ['xi1n']]
>>> pinyin('中心', style=Style.BOPOMOFO)  # 注音风格
[['ㄓㄨㄥ'], ['ㄒㄧㄣ']]
>>> pinyin('中心', style=Style.CYRILLIC)  # 俄语字母风格
[['чжун1'], ['синь1']]
>>> lazy_pinyin('中心')  # 不考虑多音字的情况
['zhong', 'xin']
# Python 3(Python 2 下把 '中心' 替换为 u'中心' 即可):

tkinter的宽与高

    from tkinter import *

    def center_window(width, height):
        screenwidth = root.winfo_screenwidth()
        screenheight = root.winfo_screenheight()
        size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
        root.geometry(size)


    root = Tk()
    center_window(700, 700)
    root.mainloop()

上面是一个tkinter设置程序居中的简单代码,其中700 700为宽高的px值,在这里没什么问题,但宽高一直都是px值么?
答案是否定的!
Text(frame, width=80, height=20, borderwidth=2, font=('黑体', '11'))
当我们使用Text文本标签时,width和height代表的是容纳字符的长度与高度。这里width代表设置80个字符的宽度,height为20个字符的高度。

程序实现

让我们先来看看实现效果吧:

界面设计

GUI的界面比较简单,只需要有一个用户文本输入,翻译按钮,结果输出即可。
可以看到说明、待注音汉字、执行结果都通过**LabelFrame**进行包裹,主要是为了美观。

整体代码

# -*- coding: utf-8 -*-
# @Author   : 王翔
# @WeChat   : King_Uranus
# @公众号    : 清风Python
# @GitHub   : https://github.com/BreezePython
# @Date     : 2019/10/10 23:19
# @Software : PyCharm
# @version  :Python 3.7.3
# @File     : WordsToPinyin.py


from tkinter import *
from pypinyin import pinyin


class WordsToPinyin:
    def __init__(self, master=None):
        self.root = master
        self.user_input = None
        self.translation = None

    def create_frame(self, text_info):
        frame = LabelFrame(self.root, text=text_info, font=('黑体', '11'), fg='red')
        frame.grid(padx=10, pady=10, sticky=NSEW)
        return frame

    def notice(self):
        frame = self.create_frame('说明')
        info = "欢迎使用【清风Python】汉语注音工具\n请将待注音的汉字或句子,填写在下方的文本框内"
        note = Label(frame, text=info, justify=LEFT, font=('黑体', '11'))
        note.grid(sticky=EW)

    def user_words(self):
        frame = self.create_frame('待注音汉字')
        self.user_input = Text(frame, width=80, height=10, borderwidth=2, font=('黑体', '11'))
        self.user_input.grid(padx=10, pady=5)

    @staticmethod
    def split_words(words):
        word_list = ""
        tmp = ""
        for string in words:
            if len(bytes(string, 'utf-8')) == 3 and len(string) == 1:
                if tmp != '':
                    word_list += tmp.ljust(6)
                    tmp = ""
                word_list += string.ljust(5)
            else:
                tmp += string
        return word_list

    def translate(self):
        self.translation.delete(0.0, END)
        total_info = ''
        info = self.user_input.get(1.0, END).split('\n')
        for line in info:
            if not line:
                continue
            a = self.split_words(line)
            total_info += ''.join(map(lambda x: x[0].ljust(6), pinyin(line))) + '\n'
            total_info += a + '\n'

        self.translation.insert(1.0, total_info)

    def start_translate(self):
        b = Button(self.root, text='开始注音', width=15, command=self.translate)
        b.grid()

    def result_info(self):
        frame = self.create_frame('执行结果')
        self.translation = Text(frame, width=80, height=20, borderwidth=2, font=('黑体', '11'))
        self.translation.grid(padx=10, pady=5)


if __name__ == '__main__':
    def center_window(width, height):
        screenwidth = root.winfo_screenwidth()
        screenheight = root.winfo_screenheight()
        size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
        root.geometry(size)


    root = Tk()
    center_window(700, 700)
    root.resizable(width=False, height=False)
    root.title('清风Python--汉字注音工具')
    Main = WordsToPinyin(root)
    Main.notice()
    Main.user_words()
    Main.start_translate()
    Main.result_info()
    root.mainloop()

程序打包

为了之后使用方便,我们可以通过pyinstaller将小程序打包成exe工具,这样就可以在电脑上直接使用了!

The End

OK,今天的内容就到这里,如果觉得内容对你有所帮助,欢迎点击文章右下角的“在看”。
公众号回复拼音即可获取整体代码及打包好的exe工具。
当然如果你是Pythoner欢迎访问我的github下载:https://github.com/BreezePython
期待你关注我的公众号 清风Python,如果觉得不错,希望能动动手指转发给你身边的朋友们。
作者:清风Python

 

 

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值