卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章20439本站已运行347

如何使用Python在Excel中替换一个单词?

如何使用Python在Excel中替换一个单词?

在Python中,我们可以使用一个名为openpyxl的第三方Python库将Excel中的一个单词替换为另一个单词。Microsoft Excel是一个用于管理和分析数据的有用工具。使用Python,我们可以自动化一些Excel数据管理任务。在本文中,我们将了解如何使用Python在Excel中替换一个单词。

安装 openpyxl

在Excel中替换Word之前,我们需要使用Python包管理器在系统中安装openpyxl库。要安装openpyxl,请在终端或命令提示符中输入以下命令。

Pip install openpyxl

语法

openpyxl.load_workbook(‘your_excel_file’)

此处,openpyxl.load_workbook() 函数从系统加载 Excel 文件。加载文件后,您可以在工作表上执行操作。

加载 Excel 电子表格

要加载一个Excel表格,我们首先需要导入openpyxl,然后使用load_workbook()函数加载电子表格,并使用workbook.active属性选择活动表。

示例

加载工作簿的代码如下所示:

import openpyxl

# Load the Excel spreadsheet
workbook = openpyxl.load_workbook('example.xlsx')

# Select the active worksheet
worksheet = workbook.active

Print("Workbook loaded")

输出

Workbook loaded

替换一个单词

要替换 Excel 中的特定单词,我们需要迭代活动 Excel 工作簿的每个单元格,检查单元格中的单词是否与我们要替换的单词匹配,然后在该单元格中插入新单词。

示例

用新单词替换旧单词的代码如下所示。

import openpyxl

# Load the Excel spreadsheet
workbook = openpyxl.load_workbook('testing.xlsx')

# Select the active worksheet
worksheet = workbook.active

# Replace the word 'old_word' with 'new_word'
for row in worksheet.iter_rows():
   for cell in row:
      if cell.value == 'old_word':
         print("Word found")
         cell.value = 'new_word'
         print("word replaced")
            
      else:
         
# Save the changes
workbook.save('testing.xlsx')

输出

Word found
word replaced

替换多个单词

如果我们想要替换Excel电子表格中的多个单词,我们可以修改前面的代码以使用字典而不是单个单词。字典中的键代表要替换的单词,值代表要替换的单词。

示例

以下代码演示了如何替换 Excel 电子表格中的多个单词 -

import openpyxl

# Load the Excel spreadsheet
workbook = openpyxl.load_workbook('example.xlsx')

# Select the active worksheet
worksheet = workbook.active

# Define the words to be replaced and their replacements
replacements = {
   'old_word_1': 'new_word_1',
   'old_word_2': 'new_word_2',
   'old_word_3': 'new_word_3'
}

# Replace the words
for row in worksheet.iter_rows():
   for cell in row:
      if cell.value in replacements:
         print("Word found")
         cell.value = replacements[cell.value]
         print("word replaced")
        
      else:
         print("word not found")

# Save the changes
workbook.save('example.xlsx')

输出

Word found
word replaced

结论

在本文中,我们讨论了如何使用 Python 的 openpyxl 库替换 Excel 中的单词。 openpyxl 提供了打开电子表格工作簿并迭代工作簿单元格的功能。我们还可以替换电子表格中的多个单词,如本文的示例之一所示。

卓越飞翔博客
上一篇: 在Python中将列表打印为表格数据
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏