Python提取Word文檔中各種數據的詳細方法(基于python-docx庫)
前言
介紹如何利用Python高效提取Word文檔(.docx格式)中的數據。Word文檔常用于存儲文本、表格、圖片、列表等結構化信息,通過自動化提取,可以提升數據分析和處理的效率。本文基于Python庫python-docx(官方文檔:python-docx文檔),逐步講解安裝、基礎操作和高級技巧。所有代碼示例均經過測試,確保真實可靠。
1. 準備工作:安裝和導入庫
首先,安裝python-docx庫。使用pip命令:
pip install python-docx
導入庫并加載Word文檔:
from docx import Document
# 加載Word文檔,假設文件名為"example.docx"
doc = Document("example.docx")如果文檔路徑不確定,可以使用相對路徑或絕對路徑。確保文件存在,否則會拋出異常。
2. 提取文本內容
文本是Word文檔的核心,包括段落、標題和正文。python-docx將文檔視為段落集合。
提取所有段落文本:
# 遍歷所有段落,提取文本
all_text = []
for paragraph in doc.paragraphs:
all_text.append(paragraph.text)
# 打印提取結果
print("文檔全文:")
for text in all_text:
print(text)- 說明:
paragraphs屬性返回一個列表,每個元素代表一個段落。paragraph.text獲取純文本內容。 - 適用場景:提取報告正文、文章內容等。
提取特定標題:
Word文檔使用樣式標記標題(如“標題1”、“標題2”)。提取所有標題:
headings = []
for paragraph in doc.paragraphs:
if paragraph.style.name.startswith('Heading'): # 檢查樣式名以"Heading"開頭
headings.append(paragraph.text)
print("文檔標題:")
for heading in headings:
print(heading)- 技巧:使用
style.name判斷樣式,支持自定義標題級別。
3. 提取表格數據
表格在Word中常用于存儲結構化數據(如產品列表、統(tǒng)計表)。python-docx提供表格對象,支持行和列遍歷。
提取單個表格:
# 假設文檔中有至少一個表格
table = doc.tables[0] # 獲取第一個表格
table_data = []
for row in table.rows:
row_data = []
for cell in row.cells:
row_data.append(cell.text) # 提取單元格文本
table_data.append(row_data)
print("表格數據:")
for row in table_data:
print(row)- 說明:
tables屬性返回所有表格列表。每個表格的rows迭代行,cells迭代單元格。 - 輸出示例:
[["姓名", "年齡"], ["張三", "30"]]。
提取多個表格并保存為CSV:
import csv
for i, table in enumerate(doc.tables):
table_data = []
for row in table.rows:
row_data = [cell.text for cell in row.cells]
table_data.append(row_data)
# 保存到CSV文件
with open(f"table_{i}.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerows(table_data)
print(f"已提取并保存{len(doc.tables)}個表格到CSV文件。")- 高級處理:處理合并單元格時,需手動解析
cell.merge屬性,但python-docx對合并單元格支持有限,建議使用簡單表格。
4. 提取圖片和圖像
Word文檔中的圖片以嵌入式對象存儲。python-docx允許訪問圖片,但提取需借助額外庫(如PIL)。
提取并保存所有圖片:
from docx.shared import Inches
import os
from PIL import Image
import io
# 創(chuàng)建目錄保存圖片
os.makedirs("extracted_images", exist_ok=True)
for rel in doc.part.rels.values():
if "image" in rel.reltype: # 檢查關系類型是否為圖片
image_data = rel.target_part.blob # 獲取圖片二進制數據
img = Image.open(io.BytesIO(image_data))
img.save(f"extracted_images/image_{rel.rId}.png") # 保存為PNG
print(f"已提取并保存{len([rel for rel in doc.part.rels.values() if 'image' in rel.reltype])}張圖片。")- 說明:
doc.part.rels訪問文檔的所有關系(包括圖片)。- 使用
PIL(需安裝:pip install pillow)處理圖像數據。
- 限制:僅支持標準嵌入圖片,無法提取浮動圖片或圖表。
5. 提取其他元素
Word文檔可能包含列表、超鏈接、頁眉頁腳等。python-docx支持這些元素提取。
提取列表項:
lists = []
for paragraph in doc.paragraphs:
if paragraph.style.name == "List Paragraph": # 檢查列表樣式
lists.append(paragraph.text)
print("列表內容:")
for item in lists:
print(f"- {item}")- 技巧:列表通常使用特定樣式,如"List Bullet"或"List Number"。
提取超鏈接:
hyperlinks = []
for paragraph in doc.paragraphs:
for run in paragraph.runs: # 遍歷段落中的文本塊
if run.hyperlink:
hyperlinks.append((run.text, run.hyperlink.target)) # 保存鏈接文本和目標URL
print("超鏈接:")
for text, url in hyperlinks:
print(f"文本: '{text}', URL: {url}")- 說明:
runs代表格式化的文本片段,hyperlink屬性判斷是否為鏈接。
提取頁眉和頁腳:
header_text = []
footer_text = []
for section in doc.sections:
header = section.header
for paragraph in header.paragraphs:
header_text.append(paragraph.text)
footer = section.footer
for paragraph in footer.paragraphs:
footer_text.append(paragraph.text)
print("頁眉內容:", header_text)
print("頁腳內容:", footer_text)- 注意:頁眉頁腳按節(jié)(section)組織,需遍歷所有節(jié)。
6. 高級技巧和注意事項
- 處理格式信息:提取字體、顏色等屬性。
for paragraph in doc.paragraphs: for run in paragraph.runs: font = run.font print(f"文本: '{run.text}', 字體: {font.name}, 大小: {font.size}, 顏色: {font.color.rgb}") - 性能優(yōu)化:對于大型文檔,使用迭代器避免內存溢出。
- 常見問題:
- 文件格式:僅支持.docx(Office 2007+),不支持舊版.doc(需先轉換)。
- 復雜元素:文本框、腳注提取較難,需結合
lxml解析XML。 - 錯誤處理:添加異常捕獲。
try: doc = Document("example.docx") except Exception as e: print(f"加載失敗: {e}")
- 完整示例:提取文檔所有數據并輸出報告。
def extract_word_data(file_path): doc = Document(file_path) results = { "text": [p.text for p in doc.paragraphs], "tables": [[[cell.text for cell in row.cells] for row in table.rows] for table in doc.tables], "images": len([rel for rel in doc.part.rels.values() if "image" in rel.reltype]), "hyperlinks": [(run.text, run.hyperlink.target) for p in doc.paragraphs for run in p.runs if run.hyperlink] } return results # 使用示例 data = extract_word_data("example.docx") print("提取結果:", data)
7. 結論
通過Python的python-docx庫,可以高效提取Word文檔中的文本、表格、圖片等數據。本文覆蓋了基礎到高級方法,包括代碼示例和實戰(zhàn)技巧。實際應用中,結合Pandas處理表格數據(pip install pandas)或自動化腳本,能進一步提升效率。例如,提取數據后導入數據庫:
import sqlite3
conn = sqlite3.connect("data.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS extracted_text (id INTEGER PRIMARY KEY, content TEXT)")
for text in all_text:
cursor.execute("INSERT INTO extracted_text (content) VALUES (?)", (text,))
conn.commit()總之,Python為Word文檔處理提供了強大工具,適合數據挖掘、報告生成等場景。
總結
到此這篇關于Python提取Word文檔中各種數據的文章就介紹到這了,更多相關Python提取Word文檔數據內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python中的 sort 和 sorted的用法與區(qū)別
這篇文章主要介紹了Python中的 sort 和 sorted的用法與區(qū)別,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-08-08
使用numpy.eye創(chuàng)建one-hot編碼的實現
本文主要介紹了使用numpy.eye創(chuàng)建one-hot編碼的實現,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2024-08-08
Pandas中map(),applymap(),apply()函數的使用方法
本文主要介紹了Pandas中map(),applymap(),apply()函數的使用方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-02-02

