起因很單純,就是給我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)