使用Python實(shí)現(xiàn)Excel中文轉(zhuǎn)拼音
在日常辦公中,我們經(jīng)常需要處理Excel文件,有時(shí)候需要將中文轉(zhuǎn)換為拼音縮寫以方便檢索和使用。今天我將分享一個(gè)使用Python開發(fā)的小工具,它可以自動(dòng)將Excel文件中指定列的中文轉(zhuǎn)換為拼音縮寫。
開發(fā)環(huán)境準(zhǔn)備
首先,我們需要安裝以下Python庫(kù):
pip install wxPython # 用于創(chuàng)建圖形界面 pip install openpyxl # 用于處理Excel文件 pip install pypinyin # 用于中文轉(zhuǎn)拼音
核心功能設(shè)計(jì)
我們的工具主要實(shí)現(xiàn)以下功能:
- 圖形界面選擇Excel文件
- 自動(dòng)定位"項(xiàng)目名稱"和"部門"列
- 中文轉(zhuǎn)換為拼音大寫縮寫
- 生成新的Excel文件
- 顯示處理結(jié)果
全部代碼
import wx import openpyxl from pypinyin import pinyin, Style import os class MainFrame(wx.Frame): def __init__(self): super().__init__(parent=None, title='Excel中文轉(zhuǎn)拼音縮寫工具', size=(500, 300)) self.init_ui() def init_ui(self): panel = wx.Panel(self) vbox = wx.BoxSizer(wx.VERTICAL) # 創(chuàng)建文件選擇按鈕 select_btn = wx.Button(panel, label='選擇Excel文件') select_btn.Bind(wx.EVT_BUTTON, self.on_select) vbox.Add(select_btn, 0, wx.ALL | wx.CENTER, 20) # 創(chuàng)建狀態(tài)顯示文本框 self.status_text = wx.TextCtrl(panel, style=wx.TE_MULTILINE | wx.TE_READONLY) vbox.Add(self.status_text, 1, wx.ALL | wx.EXPAND, 20) panel.SetSizer(vbox) self.Centre() def on_select(self, event): with wx.FileDialog(self, "選擇Excel文件", wildcard="Excel files (*.xlsx)|*.xlsx", style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog: if fileDialog.ShowModal() == wx.ID_CANCEL: return pathname = fileDialog.GetPath() try: self.process_excel(pathname) except Exception as e: wx.MessageBox(f'處理文件時(shí)發(fā)生錯(cuò)誤:{str(e)}', '錯(cuò)誤', wx.OK | wx.ICON_ERROR) def get_pinyin_abbr(self, chinese_str): """獲取中文的拼音縮寫""" if not chinese_str or not isinstance(chinese_str, str): return chinese_str # 獲取每個(gè)字的拼音首字母 abbr = '' for p in pinyin(chinese_str, style=Style.FIRST_LETTER): abbr += p[0].upper() return abbr def process_excel(self, filepath): """處理Excel文件""" self.status_text.SetValue("開始處理文件...\n") # 加載工作簿 wb = openpyxl.load_workbook(filepath) ws = wb.active # 查找目標(biāo)列的索引 project_col = None dept_col = None for col in range(1, ws.max_column + 1): cell_value = ws.cell(row=2, column=col).value # 假設(shè)第2行是標(biāo)題行 if cell_value == "項(xiàng)目名稱": project_col = col elif cell_value == "部門": dept_col = col if not project_col or not dept_col: raise ValueError("未找到'項(xiàng)目名稱'或'部門'列") # 轉(zhuǎn)換內(nèi)容 changes = [] for row in range(3, ws.max_row + 1): # 從第3行開始處理 # 處理項(xiàng)目名稱 project_cell = ws.cell(row=row, column=project_col) if project_cell.value: original_project = project_cell.value project_cell.value = self.get_pinyin_abbr(original_project) changes.append(f"行 {row}: 項(xiàng)目名稱 '{original_project}' -> '{project_cell.value}'") # 處理部門 dept_cell = ws.cell(row=row, column=dept_col) if dept_cell.value: original_dept = dept_cell.value dept_cell.value = self.get_pinyin_abbr(original_dept) changes.append(f"行 {row}: 部門 '{original_dept}' -> '{dept_cell.value}'") # 生成新文件名 file_dir = os.path.dirname(filepath) file_name = os.path.basename(filepath) new_file_name = f"pinyin_{file_name}" new_filepath = os.path.join(file_dir, new_file_name) # 保存新文件 wb.save(new_filepath) # 更新狀態(tài) status_msg = "\n".join(changes) self.status_text.AppendText(f"\n轉(zhuǎn)換完成!更改詳情:\n{status_msg}\n\n新文件已保存為:{new_filepath}") def main(): app = wx.App() frame = MainFrame() frame.Show() app.MainLoop() if __name__ == '__main__': main()
1. 創(chuàng)建圖形界面
首先,我們使用wxPython創(chuàng)建一個(gè)簡(jiǎn)單的圖形界面:
class MainFrame(wx.Frame): def __init__(self): super().__init__(parent=None, title='Excel中文轉(zhuǎn)拼音縮寫工具', size=(500, 300)) self.init_ui() def init_ui(self): panel = wx.Panel(self) vbox = wx.BoxSizer(wx.VERTICAL) # 創(chuàng)建文件選擇按鈕 select_btn = wx.Button(panel, label='選擇Excel文件') select_btn.Bind(wx.EVT_BUTTON, self.on_select) vbox.Add(select_btn, 0, wx.ALL | wx.CENTER, 20) # 創(chuàng)建狀態(tài)顯示文本框 self.status_text = wx.TextCtrl(panel, style=wx.TE_MULTILINE | wx.TE_READONLY) vbox.Add(self.status_text, 1, wx.ALL | wx.EXPAND, 20) panel.SetSizer(vbox) self.Centre()
2. 實(shí)現(xiàn)文件選擇功能
添加文件選擇對(duì)話框和錯(cuò)誤處理:
def on_select(self, event): with wx.FileDialog(self, "選擇Excel文件", wildcard="Excel files (*.xlsx)|*.xlsx", style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog: if fileDialog.ShowModal() == wx.ID_CANCEL: return pathname = fileDialog.GetPath() try: self.process_excel(pathname) except Exception as e: wx.MessageBox(f'處理文件時(shí)發(fā)生錯(cuò)誤:{str(e)}', '錯(cuò)誤', wx.OK | wx.ICON_ERROR)
3. 中文轉(zhuǎn)拼音功能
使用pypinyin庫(kù)實(shí)現(xiàn)中文轉(zhuǎn)拼音縮寫:
def get_pinyin_abbr(self, chinese_str): """獲取中文的拼音縮寫""" if not chinese_str or not isinstance(chinese_str, str): return chinese_str # 獲取每個(gè)字的拼音首字母 abbr = '' for p in pinyin(chinese_str, style=Style.FIRST_LETTER): abbr += p[0].upper() return abbr
4. Excel處理核心功能
實(shí)現(xiàn)Excel文件的讀取、處理和保存:
def process_excel(self, filepath): """處理Excel文件""" self.status_text.SetValue("開始處理文件...\n") # 加載工作簿 wb = openpyxl.load_workbook(filepath) ws = wb.active # 查找目標(biāo)列的索引 project_col = None dept_col = None for col in range(1, ws.max_column + 1): cell_value = ws.cell(row=2, column=col).value if cell_value == "項(xiàng)目名稱": project_col = col elif cell_value == "部門": dept_col = col # 轉(zhuǎn)換內(nèi)容并保存 # ... (詳細(xì)代碼見完整實(shí)現(xiàn))
技術(shù)要點(diǎn)解析
1.wxPython使用技巧
- 使用BoxSizer進(jìn)行界面布局
- 添加文件選擇對(duì)話框
- 實(shí)現(xiàn)事件綁定
2.Excel處理技巧
- 使用openpyxl讀寫Excel文件
- 動(dòng)態(tài)查找目標(biāo)列
- 保持原始格式不變
3.中文轉(zhuǎn)拼音處理
- 使用pypinyin庫(kù)處理中文
- 提取拼音首字母
- 處理異常情況
使用效果
運(yùn)行程序后顯示簡(jiǎn)潔的操作界面
點(diǎn)擊按鈕選擇Excel文件
自動(dòng)處理并生成新文件
界面實(shí)時(shí)顯示處理進(jìn)度和結(jié)果
實(shí)際應(yīng)用案例
比如有以下數(shù)據(jù):
- 項(xiàng)目名稱:智能消防工程
- 部門:消防支隊(duì)
轉(zhuǎn)換后變?yōu)椋?/p>
- 項(xiàng)目名稱:ZNXFGC
- 部門:XFZD
注意事項(xiàng)
確保Excel文件格式正確
表格第2行必須是標(biāo)題行
從第3行開始處理數(shù)據(jù)
原文件不會(huì)被修改
未來優(yōu)化方向
添加自定義列選擇功能
支持更多Excel格式
添加批量處理功能
優(yōu)化轉(zhuǎn)換規(guī)則
運(yùn)行結(jié)果
到此這篇關(guān)于使用Python實(shí)現(xiàn)Excel中文轉(zhuǎn)拼音的文章就介紹到這了,更多相關(guān)Python Excel中文轉(zhuǎn)拼音內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
django中send_mail功能實(shí)現(xiàn)詳解
這篇文章主要給大家介紹了關(guān)于django中send_mail功能實(shí)現(xiàn)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-02-02python內(nèi)置函數(shù)sorted()用法深入分析
這篇文章主要介紹了python內(nèi)置函數(shù)sorted()用法,結(jié)合實(shí)例形式較為深入的分析了Python內(nèi)置函數(shù)sorted()功能、使用方法及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下2019-10-10python實(shí)現(xiàn)通過隊(duì)列完成進(jìn)程間的多任務(wù)功能示例
這篇文章主要介紹了python實(shí)現(xiàn)通過隊(duì)列完成進(jìn)程間的多任務(wù)功能,結(jié)合實(shí)例形式分析了Python隊(duì)列完成進(jìn)程間的多任務(wù)以及進(jìn)程池pool相關(guān)操作技巧,需要的朋友可以參考下2019-10-10python實(shí)現(xiàn)學(xué)生管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)學(xué)生管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01Python如何把Spark數(shù)據(jù)寫入ElasticSearch
這篇文章主要介紹了Python如何把Spark數(shù)據(jù)寫入ElasticSearch,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04一文讓你徹底搞懂Python中__str__和__repr__
這篇文章主要介紹了Python中的__str__和__repr__的異同,__str__和__repr__是基本的內(nèi)置方法,文中有詳細(xì)的代碼示例,感興趣的同學(xué)可以參考閱讀下2023-05-05scrapy在python爬蟲中搭建出錯(cuò)的解決方法
在本篇文章里小編給大家整理了一篇關(guān)于scrapy在python爬蟲中搭建出錯(cuò)的解決方法,有需要的朋友們可以學(xué)習(xí)參考下。2020-11-11python?pandas分割DataFrame中的字符串及元組的方法實(shí)現(xiàn)
本文主要介紹了python?pandas分割DataFrame中的字符串及元組的方法實(shí)現(xiàn),主要介紹了3種方法,具有一定的參考價(jià)值,感興趣的可以了解一下2022-03-03