python
主页 > 脚本 > python >

使用Python实现Excel中文转拼音

2025-02-23 | 佚名 | 点击:

在日常办公中,我们经常需要处理Excel文件,有时候需要将中文转换为拼音缩写以方便检索和使用。今天我将分享一个使用Python开发的小工具,它可以自动将Excel文件中指定列的中文转换为拼音缩写。

开发环境准备

首先,我们需要安装以下Python库:

1

2

3

pip install wxPython    # 用于创建图形界面

pip install openpyxl    # 用于处理Excel文件

pip install pypinyin    # 用于中文转拼音

核心功能设计

我们的工具主要实现以下功能:

全部代码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

import wx

import openpyxl

from pypinyin import pinyin, Style

import os

 

class MainFrame(wx.Frame):

    def __init__(self):

        super().__init__(parent=None, title='Excel中文转拼音缩写工具', size=(500, 300))

        self.init_ui()

         

    def init_ui(self):

        panel = wx.Panel(self)

        vbox = wx.BoxSizer(wx.VERTICAL)

         

        # 创建文件选择按钮

        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)

         

        # 创建状态显示文本框

        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'处理文件时发生错误:{str(e)}', '错误',

                            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

             

        # 获取每个字的拼音首字母

        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

         

        # 查找目标列的索引

        project_col = None

        dept_col = None

         

        for col in range(1, ws.max_column + 1):

            cell_value = ws.cell(row=2, column=col).value  # 假设第2行是标题行

            if cell_value == "项目名称":

                project_col = col

            elif cell_value == "部门":

                dept_col = col

         

        if not project_col or not dept_col:

            raise ValueError("未找到'项目名称'或'部门'列")

         

        # 转换内容

        changes = []

        for row in range(3, ws.max_row + 1):  # 从第3行开始处理

            # 处理项目名称

            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}: 项目名称 '{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)

         

        # 更新状态

        status_msg = "\n".join(changes)

        self.status_text.AppendText(f"\n转换完成!更改详情:\n{status_msg}\n\n新文件已保存为:{new_filepath}")

 

def main():

    app = wx.App()

    frame = MainFrame()

    frame.Show()

    app.MainLoop()

 

if __name__ == '__main__':

    main()

1. 创建图形界面

首先,我们使用wxPython创建一个简单的图形界面:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

class MainFrame(wx.Frame):

    def __init__(self):

        super().__init__(parent=None, title='Excel中文转拼音缩写工具', size=(500, 300))

        self.init_ui()

         

    def init_ui(self):

        panel = wx.Panel(self)

        vbox = wx.BoxSizer(wx.VERTICAL)

         

        # 创建文件选择按钮

        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)

         

        # 创建状态显示文本框

        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. 实现文件选择功能

添加文件选择对话框和错误处理:

1

2

3

4

5

6

7

8

9

10

11

12

13

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'处理文件时发生错误:{str(e)}', '错误',

                        wx.OK | wx.ICON_ERROR)

3. 中文转拼音功能

使用pypinyin库实现中文转拼音缩写:

1

2

3

4

5

6

7

8

9

10

def get_pinyin_abbr(self, chinese_str):

    """获取中文的拼音缩写"""

    if not chinese_str or not isinstance(chinese_str, str):

        return chinese_str

         

    # 获取每个字的拼音首字母

    abbr = ''

    for p in pinyin(chinese_str, style=Style.FIRST_LETTER):

        abbr += p[0].upper()

    return abbr

4. Excel处理核心功能

实现Excel文件的读取、处理和保存:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

def process_excel(self, filepath):

    """处理Excel文件"""

    self.status_text.SetValue("开始处理文件...\n")

     

    # 加载工作簿

    wb = openpyxl.load_workbook(filepath)

    ws = wb.active

     

    # 查找目标列的索引

    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 == "项目名称":

            project_col = col

        elif cell_value == "部门":

            dept_col = col

     

    # 转换内容并保存

    # ... (详细代码见完整实现)

技术要点解析

1.wxPython使用技巧

2.Excel处理技巧

3.中文转拼音处理

使用效果

运行程序后显示简洁的操作界面

点击按钮选择Excel文件

自动处理并生成新文件

界面实时显示处理进度和结果

实际应用案例

比如有以下数据:

转换后变为:

注意事项

确保Excel文件格式正确

表格第2行必须是标题行

从第3行开始处理数据

原文件不会被修改

未来优化方向

添加自定义列选择功能

支持更多Excel格式

添加批量处理功能

优化转换规则

运行结果

原文链接:
相关文章
最新更新