Python提取Word文檔中各種數(shù)據(jù)的詳細(xì)方法(基于python-docx庫)
前言
介紹如何利用Python高效提取Word文檔(.docx格式)中的數(shù)據(jù)。Word文檔常用于存儲文本、表格、圖片、列表等結(jié)構(gòu)化信息,通過自動化提取,可以提升數(shù)據(jù)分析和處理的效率。本文基于Python庫python-docx(官方文檔:python-docx文檔),逐步講解安裝、基礎(chǔ)操作和高級技巧。所有代碼示例均經(jīng)過測試,確保真實(shí)可靠。
1. 準(zhǔn)備工作:安裝和導(dǎo)入庫
首先,安裝python-docx庫。使用pip命令:
pip install python-docx
導(dǎo)入庫并加載Word文檔:
from docx import Document
# 加載Word文檔,假設(shè)文件名為"example.docx"
doc = Document("example.docx")如果文檔路徑不確定,可以使用相對路徑或絕對路徑。確保文件存在,否則會拋出異常。
2. 提取文本內(nèi)容
文本是Word文檔的核心,包括段落、標(biāo)題和正文。python-docx將文檔視為段落集合。
提取所有段落文本:
# 遍歷所有段落,提取文本
all_text = []
for paragraph in doc.paragraphs:
all_text.append(paragraph.text)
# 打印提取結(jié)果
print("文檔全文:")
for text in all_text:
print(text)- 說明:
paragraphs屬性返回一個列表,每個元素代表一個段落。paragraph.text獲取純文本內(nèi)容。 - 適用場景:提取報(bào)告正文、文章內(nèi)容等。
提取特定標(biāo)題:
Word文檔使用樣式標(biāo)記標(biāo)題(如“標(biāo)題1”、“標(biāo)題2”)。提取所有標(biāo)題:
headings = []
for paragraph in doc.paragraphs:
if paragraph.style.name.startswith('Heading'): # 檢查樣式名以"Heading"開頭
headings.append(paragraph.text)
print("文檔標(biāo)題:")
for heading in headings:
print(heading)- 技巧:使用
style.name判斷樣式,支持自定義標(biāo)題級別。
3. 提取表格數(shù)據(jù)
表格在Word中常用于存儲結(jié)構(gòu)化數(shù)據(jù)(如產(chǎn)品列表、統(tǒng)計(jì)表)。python-docx提供表格對象,支持行和列遍歷。
提取單個表格:
# 假設(shè)文檔中有至少一個表格
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("表格數(shù)據(jù):")
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文件。")- 高級處理:處理合并單元格時(shí),需手動解析
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: # 檢查關(guān)系類型是否為圖片
image_data = rel.target_part.blob # 獲取圖片二進(jìn)制數(shù)據(jù)
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訪問文檔的所有關(guān)系(包括圖片)。- 使用
PIL(需安裝:pip install pillow)處理圖像數(shù)據(jù)。
- 限制:僅支持標(biāo)準(zhǔn)嵌入圖片,無法提取浮動圖片或圖表。
5. 提取其他元素
Word文檔可能包含列表、超鏈接、頁眉頁腳等。python-docx支持這些元素提取。
提取列表項(xiàng):
lists = []
for paragraph in doc.paragraphs:
if paragraph.style.name == "List Paragraph": # 檢查列表樣式
lists.append(paragraph.text)
print("列表內(nèi)容:")
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)) # 保存鏈接文本和目標(biāo)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("頁眉內(nèi)容:", header_text)
print("頁腳內(nèi)容:", footer_text)- 注意:頁眉頁腳按節(jié)(section)組織,需遍歷所有節(jié)。
6. 高級技巧和注意事項(xiàng)
- 處理格式信息:提取字體、顏色等屬性。
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)化:對于大型文檔,使用迭代器避免內(nèi)存溢出。
- 常見問題:
- 文件格式:僅支持.docx(Office 2007+),不支持舊版.doc(需先轉(zhuǎn)換)。
- 復(fù)雜元素:文本框、腳注提取較難,需結(jié)合
lxml解析XML。 - 錯誤處理:添加異常捕獲。
try: doc = Document("example.docx") except Exception as e: print(f"加載失敗: {e}")
- 完整示例:提取文檔所有數(shù)據(jù)并輸出報(bào)告。
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("提取結(jié)果:", data)
7. 結(jié)論
通過Python的python-docx庫,可以高效提取Word文檔中的文本、表格、圖片等數(shù)據(jù)。本文覆蓋了基礎(chǔ)到高級方法,包括代碼示例和實(shí)戰(zhàn)技巧。實(shí)際應(yīng)用中,結(jié)合Pandas處理表格數(shù)據(jù)(pip install pandas)或自動化腳本,能進(jìn)一步提升效率。例如,提取數(shù)據(jù)后導(dǎo)入數(shù)據(jù)庫:
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文檔處理提供了強(qiáng)大工具,適合數(shù)據(jù)挖掘、報(bào)告生成等場景。
總結(jié)
到此這篇關(guān)于Python提取Word文檔中各種數(shù)據(jù)的文章就介紹到這了,更多相關(guān)Python提取Word文檔數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python中的 sort 和 sorted的用法與區(qū)別
這篇文章主要介紹了Python中的 sort 和 sorted的用法與區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08
django進(jìn)階之cookie和session的使用示例
這篇文章主要介紹了django進(jìn)階之cookie和session的使用示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08
使用numpy.eye創(chuàng)建one-hot編碼的實(shí)現(xiàn)
本文主要介紹了使用numpy.eye創(chuàng)建one-hot編碼的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-08-08
Pandas中map(),applymap(),apply()函數(shù)的使用方法
本文主要介紹了Pandas中map(),applymap(),apply()函數(shù)的使用方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02

