基于Python第三方插件实现西游记章节标注汉语拼音

      起因很单纯,就是给我1年级小豆包的女儿标注三国和西游章节的汉语拼音,我女儿每天都朗读 ,结果有很多字不认识,我爱人居然让我给标记不认识的完了手动注音......我勒个去......身为程序员的我怎么能忘记用程序实现呢,特别是咱也会点Python万能语言。哈哈!列举一下使用的技术。

语言:Python3.7

插件:pypinyin0.37.0  和 openpyxl 3.0.3

开发工具:pycharm 社区版

使用openpyxl操作execl的教程多的你无法想。

使用pypinyin将汉字转换成汉语拼音很简单,网络上API一大推。而且简单的不能再简单了,就一句话就实现了。分享点代码:

# 带声调的(默认)
def yinjie(word):
    sentens = "".join(word.split())
    print(sentens)
    s = ''
    # heteronym=True开启多音字
    for i in pypinyin.pinyin(word, heteronym=False):
        s = s + ''.join(i) + " "
    return s

这个就足够汉字转拼音了,不过我要求数据结构就没使用这个方法。我把数据结构说一下。

三层二维数组(这个非常关键):

第一层:单个汉字和汉语拼音构成。

['dì', '第'], ['yī', '一'], ['bǎi', '百'], ['huí', '回']

第二层:按照标题空格分词。

[['dì', '第'], ['yī', '一'], ['bǎi', '百'], ['huí', '回']], [['jìng', '径'], ['huí', '回'], ['dōng', '东'], ['tǔ', '土']], [['wǔ', '五'], ['shèng', '圣'], ['chéng', '成'], ['zhēn', '真']]

第三层:所有标题的集合。

就是第二层的合计,西游记就是100个章节标题集合。

最开始的成果物。这个不好对应也很难阅读。

我爱人给了我一个参考事例。如下图:

咱也不能示弱,咱也是程序员。咱也会万能的Python。

最开始的目标是将文字写入到word中,所以就用了Python-docx。汉语拼音长短不一这个很难对齐。想计算汉语拼音的长度进而计算汉字的位置......这个算法得多复杂,一个排版算法...我不是大神......

这个玩意其实和数学应用题一样,想到了其实一点也不难,就是弄个表格完了让汉语拼音和汉字居中不就得了。想到这个以后其实一点都不难了。使用Python-docx搞了好久有个问题就是竖版的word放不下汉字和汉语拼音。头疼啊。效果如下图:

唉!难道是思路不对。。。

不用Python-docx了。使用openpyxl来操作execl。第一次成果物。看起来还可以。

最终的成果物。

转成PDF的成果物:

继续鼓捣,最终搞定。。。一共花费了近6个小时,时间有点多。其实主要是数据结构和排版耽误时间,在有就是语法,作为Net出身而后转Java的人来说这个…&...就是并且的意思。然而在Python里面他不就是并且是and啊啊啊啊啊!因为这个我改了N多代码调试了好几次,唉深度无语。真是基础不牢地动山摇啊。别废话了上代码:

import pypinyin

from openpyxl import Workbook
from openpyxl.drawing.text import Font
from openpyxl.styles import Font, colors, Alignment

from pulgin.Tools import Tools

class HanZhiAddPinYin:
    def __init__(self):
        pass

    def signWord(self,word):
        pinyicontent = pypinyin.pinyin(word, heteronym=False)
        word_pinyin = [pinyicontent[0][0], word]
        return word_pinyin

    def sentences(self,keyWords):
        listsentense = []
        for duanyu in keyWords.split():
            print(duanyu)
            duanyu_list = []
            for word in duanyu:
                duanyu_list.append(self.signWord(word))
            listsentense.append(duanyu_list)
        print(
            listsentense
        )
        return listsentense

    def articles(self,txt_file_path):
        article = []
        encoding = Tools.get_file_encoding(txt_file_path)
        f = open(txt_file_path, "r", encoding=encoding, errors='ignore')  # 返回一个文件对象
        line = f.readline().strip()  # 调用文件的 readline()方法
        index = 1
        while line:
            article.append(self.sentences(line))
            line = f.readline()
            index = index + 1
        f.close()
        return article

    def builder_execl(self,word_title, save_path, article):
        """
        构建execl文件
        :param word_title: sheet页面的名词
        :param save_path: execl保存路径
        :param article:  文章内容集合
        :return:
        """
        wb = Workbook()
        ws = wb.active
        ws.title = word_title
        ws.sheet_properties.tabColor = "1072BA"  # 设置背景
        xl_sheet = wb.get_sheet_by_name(word_title)
        execl_cell_width = 4.6
        for sentences in article:
            column_index = 1
            # sentences 2行数据
            # 获取行数
            pinyin_row = xl_sheet.max_row + 1  # 拼音所在的行
            hanzi_row = pinyin_row + 1  # 汉字所在的行
            sentences_index = 0
            for duanyu in sentences:  # ['dì', '第'], ['yī', '一'], ['huí', '回']
                for sign_word in duanyu:  # ['dì', '第']

                    # region 设置样式
                    # 设置样式
                    execl_cell_font = Font(name='华文楷体', size=12, italic=False, color=colors.BLACK, bold=True)
                    execl_pinyin_row = xl_sheet.cell(row=pinyin_row, column=column_index)
                    execl_hanzi_row = xl_sheet.cell(row=hanzi_row, column=column_index)
                    execl_pinyin_row.alignment = Alignment(horizontal='center', vertical='center')
                    execl_hanzi_row.alignment = Alignment(horizontal='center', vertical='center')
                    execl_pinyin_row.font = execl_cell_font
                    execl_hanzi_row.font = execl_cell_font

                    xl_sheet.column_dimensions['A'].width = 3
                    xl_sheet.column_dimensions['B'].width = 3
                    xl_sheet.column_dimensions['C'].width = 3
                    xl_sheet.column_dimensions['D'].width = execl_cell_width
                    xl_sheet.column_dimensions['E'].width = execl_cell_width
                    xl_sheet.column_dimensions['F'].width = execl_cell_width
                    xl_sheet.column_dimensions['H'].width = execl_cell_width
                    xl_sheet.column_dimensions['I'].width = execl_cell_width
                    xl_sheet.column_dimensions['G'].width = execl_cell_width
                    xl_sheet.column_dimensions['J'].width = execl_cell_width
                    xl_sheet.column_dimensions['K'].width = execl_cell_width
                    xl_sheet.column_dimensions['L'].width = execl_cell_width
                    xl_sheet.column_dimensions['M'].width = execl_cell_width
                    xl_sheet.column_dimensions['N'].width = execl_cell_width
                    xl_sheet.column_dimensions['O'].width = execl_cell_width
                    xl_sheet.column_dimensions['P'].width = execl_cell_width
                    xl_sheet.column_dimensions['Q'].width = execl_cell_width
                    xl_sheet.column_dimensions['R'].width = execl_cell_width
                    xl_sheet.column_dimensions['S'].width = execl_cell_width
                    xl_sheet.column_dimensions['T'].width = execl_cell_width
                    xl_sheet.column_dimensions['U'].width = execl_cell_width
                    xl_sheet.column_dimensions['V'].width = execl_cell_width
                    xl_sheet.column_dimensions['W'].width = execl_cell_width
                    # endregion

                    xl_sheet.cell(row=pinyin_row, column=column_index, value=sign_word[0])
                    xl_sheet.cell(row=hanzi_row, column=column_index, value=sign_word[1])  # 0 第一百回  1 径回东土 2 五圣成真
                    # print(sentences_index)
                    # print(len(duanyu) + len(sentences[0]))
                    # print(column_index)
                    if sentences_index == 1 and len(duanyu) + len(sentences[0]) == column_index:#坑人的and
                        xl_sheet.cell(row=pinyin_row, column=column_index + 1, value=",")
                        xl_sheet.cell(row=hanzi_row, column=column_index + 1, value=",")
                        column_index = column_index + 1  # 遇到断句多增加一列向后
                    column_index = column_index + 1  # 列向后
                sentences_index = sentences_index + 1  # 三个短语计数器
        wb.save(save_path)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章