Python實現(xiàn)Word文檔中提取表格數(shù)據(jù)并轉換為CSV和JSON格式
前言
在日常工作中,我們經常需要處理大量的Word文檔,其中包含各種表格數(shù)據(jù)。手動整理這些表格不僅耗時且容易出錯。因此,開發(fā)一個自動化工具來解析Word文檔中的表格,并將其轉換為更易于處理的CSV或JSON格式,可以極大地提高工作效率。
1.解析Word文檔中的表格
Python提供了多個庫來幫助我們實現(xiàn)這一目標,其中python-docx庫非常適合讀取Word文檔(.docx)的內容。下面的代碼示例展示了一個名為extract_tables_from_docx的函數(shù),該函數(shù)接收一個Word文檔的路徑作為輸入,然后解析文檔中的所有表格,并將每個表格的數(shù)據(jù)以嵌套列表的形式返回。
首先導入必要的庫
import os import csv import json from docx import Document from collections import defaultdict from lxml import etree
def extract_tables_from_docx(docx_path):
doc = Document(docx_path)
all_tables_data = []
for table in doc.tables:
table_data = []
merged_cells = defaultdict(str)
row_spans = defaultdict(lambda: 0)
for i, row in enumerate(table.rows):
row_data = []
for j, cell in enumerate(row.cells):
cell_text = cell.text.strip()
cell_xml = etree.fromstring(cell._element.xml)
nsmap = {'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'}
grid_span = cell_xml.xpath(".//w:gridSpan/@w:val", namespaces=nsmap)
if grid_span:
span = int(grid_span[0])
for k in range(span):
if k == 0:
row_data.append(cell_text)
else:
merged_cells[(i, j + k)] = cell_text
else:
row_data.append(cell_text)
v_merge = cell_xml.xpath(".//w:vMerge/@w:val", namespaces=nsmap)
if v_merge:
if v_merge[0] == 'restart':
row_spans[(i, j)] = 1
merged_cells[(i, j)] = cell_text
elif v_merge[0] is None:
row_spans[(i, j)] += 1
row_data[-1] = merged_cells[(i - row_spans[(i, j)], j)]
table_data.append(row_data)
all_tables_data.append(table_data)
return all_tables_data
該函數(shù)使用了lxml庫來解析XML,因為.docx文件本質上是ZIP壓縮包,其中包含了用于描述文檔結構的XML文件。lxml庫允許通過XPath查詢來訪問這些XML元素,從而處理單元格的合并和跨度。
2.保存表格數(shù)據(jù)
一旦表格數(shù)據(jù)被提取出來,就可以將其保存為CSV或JSON格式。為此,定義了兩個輔助函數(shù)save_tables_to_csv和save_tables_to_json,它們分別負責將表格數(shù)據(jù)寫入CSV文件和JSON文件。
def save_tables_to_csv(tables, output_dir, file_name):
for i, table in enumerate(tables):
csv_path = os.path.join(output_dir, f"{file_name}_table_{i+1}.csv")
with open(csv_path, mode='w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerows(table)
print(f"表格 {i+1} 已保存為 CSV 文件,路徑為 {csv_path}")
def save_tables_to_json(tables, output_dir, file_name):
for i, table in enumerate(tables):
json_path = os.path.join(output_dir, f"{file_name}_table_{i+1}.json")
with open(json_path, mode='w', encoding='utf-8') as file:
json.dump(table, file, ensure_ascii=False, indent=4)
print(f"表格 {i+1} 已保存為 JSON 文件,路徑為 {json_path}")
3.處理文件夾中的多個Word文檔
為了批量處理文件夾中的多個Word文檔,我們可以使用os.listdir和列表推導式來獲取所有.doc或.docx文件的列表。然后,對于列表中的每個文件,我們調用上述函數(shù)來提取表格并保存結果。
# 設置文件路徑和輸出目錄
docx_path = r'E:\data\\測試表格'
output_dir = r'E:\data\\測試表格'
# 獲取文件夾中所有 Word 文件的列表
word_files = [f for f in os.listdir(docx_path) if f.endswith('.doc') or f.endswith('.docx')]
# 提取表格數(shù)據(jù)并保存為 CSV 和 JSON 文件
for file in word_files:
file_path = os.path.join(docx_path, file)
tables = extract_tables_from_docx(file_path)
file_name = os.path.splitext(file)[0]
save_tables_to_csv(tables, output_dir, file_name)
save_tables_to_json(tables, output_dir, file_name)
4.總結
通過這個腳本,可以輕松地從Word文檔中提取表格數(shù)據(jù),并將其轉換為CSV或JSON格式,從而方便進一步的數(shù)據(jù)分析或導入到數(shù)據(jù)庫中。節(jié)省了手動數(shù)據(jù)錄入的時間,還減少了人為錯誤的可能性,提高了數(shù)據(jù)處理的效率和準確性。
以上就是Python實現(xiàn)Word文檔中提取表格數(shù)據(jù)并轉換為CSV和JSON格式的詳細內容,更多關于Python Word數(shù)據(jù)提取并轉為CSV和JSON的資料請關注腳本之家其它相關文章!
相關文章
Python結合FastSAM實現(xiàn)圖像自動標注的完整指南
FastSAM是SAM的加速版本,能夠在保持較高精度的同時大幅提升處理速度,本文將詳細解析Python結合FastSAM實現(xiàn)圖像自動標注的代碼結構、實現(xiàn)原理和使用方法,幫助讀者快速掌握圖像自動標注的核心技術2025-10-10
使用python將請求的requests headers參數(shù)格式化方法
今天小編就為大家分享一篇使用python將請求的requests headers參數(shù)格式化方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01

