本文詳細介紹如何使用 Python 的 win32com 模組讀取並轉換 Microsoft Word 文檔(.doc/.docx)為純文字或其他格式。透過 COM 自動化介面操作 Word 應用程式,適合 Windows 環境下的批次文件處理需求。
首先安裝 pywin32 套件(包含 win32com):
pip install pywin32
以下程式碼開啟 Word 文件,另存為純文字(格式代碼 4 對應 wdFormatText),並關閉應用程式:
from win32com import client as wc
word = wc.Dispatch('Word.Application')
doc = word.Documents.Open(r'C:\test.docx')
doc.SaveAs(r'C:\test', 4) # 4 = wdFormatText
doc.Close()
word.Quit()
注意: 儲存時若不指定副檔名,Word 會自動附加 .txt。若需以 Python 內建 open(..., 'r') 讀取,請確保使用格式代碼 4(而非 2)。
下表列出 SaveAs 方法常用的 FileFormat 參數值(部分代碼需 Office 2007 以上版本支援):
| 常數名稱 | 代碼 | 說明 |
|---|---|---|
| wdFormatDocument | 0 | Word 97-2003 文檔 (.doc) |
| wdFormatDocumentDefault | 16 | 預設格式 (.docx) |
| wdFormatText | 2 | 純文字 (ANSI) |
| wdFormatDOSText | 4 | 純文字 (DOS),適合 Python 讀取 |
| wdFormatUnicodeText | 7 | Unicode 文字 |
| wdFormatRTF | 6 | Rich Text Format (.rtf) |
| wdFormatHTML | 8 | HTML 格式,含 OLE 物件 (WMF) |
| wdFormatFilteredHTML | 10 | 過濾後 HTML,較乾淨,公式轉 GIF |
| wdFormatPDF | 17 | PDF 格式 |
| wdFormatXMLDocument | 12 | Word XML (.xml) |
補充說明: wdFormatHTML (8) 會將公式等 OLE 物件存為 WMF 向量圖;wdFormatFilteredHTML (10) 則轉為 GIF 位圖,產出的 HTML 碼較精簡。
結合正則表達式,可從轉出的文字檔中擷取特定模式(如選項 A-D)、產出題目與答案檔:
import re
from win32com import client as wc
word = wc.Dispatch('Word.Application')
doc = word.Documents.Open(r'C:\test1.doc')
doc.SaveAs(r'C:\test1', 4) # 轉純文字
doc.Close()
word.Quit()
# 讀取文字並擷取選項
with open(r'C:\test1.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 範例:找出 (A)、(B)等格式
pattern = r'(\(?\s*[A-D]\s*\)?)|(【\s*[A-D]\s*】)'
cleaned = re.sub(pattern, '()', text)
with open(r'C:\question.txt', 'a', encoding='utf-8') as qf:
qf.write(cleaned)
# 擷取答案
answers = re.findall(pattern, text)
with open(r'C:\answeronly.txt', 'a', encoding='utf-8') as af:
for idx, ans in enumerate(answers, 1):
match = re.search(r'[A-D]', ans[0] or ans[1])
if match:
af.write(f'{idx} {match.group()}\n')
同樣透過 COM 介面,PHP、C# 等語言亦可調用 Word API 實現相同功能,僅語法不同。
win32com.client.Dispatch('Word.Application') 啟動 Word 實例。Documents.Open 開啟檔案,SaveAs 指定格式代碼轉換。Quit() 釋放資源,避免殘留進程。wdFormatDOSText) 最適合後續 Python 文字處理。掌握此技巧,即可自動化處理大量 Word 文檔轉檔、內容擷取等作業,大幅提升效率。