如何使用 Python 替換 Excel 中的單詞?
在 Python 中,我們可以使用一個名為 **openpyxl** 的第三方 Python 庫來替換 Excel 中的單詞。Microsoft Excel 是一款用於資料管理和分析的有用工具。使用 Python,我們可以自動化一些 Excel 資料管理任務。在本文中,我們將瞭解如何使用 Python 替換 Excel 中的單詞。
安裝 openpyxl
在實現替換 Excel 中單詞的程式之前,我們需要使用 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 提供了開啟電子表格工作簿並遍歷工作簿單元格的功能。我們還可以替換電子表格中的多個單詞,如本文中的一個示例所示。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP