python-docx读取docx
时间: 2025-05-09 07:22:33 浏览: 25
### 使用 `python-docx` 库读取 DOCX 文件内容
#### 安装依赖
为了使用 `python-docx`,需要先通过以下命令安装该库:
```bash
pip install python-docx
```
需要注意的是,`python-docx` 只能操作 `.docx` 格式的文件,如果遇到 `.doc` 文件,则需将其转换为 `.docx` 后再进行处理[^1]。
---
#### 基本方法:读取文档中的段落文本
以下是利用 `python-docx` 读取 `.docx` 文件中所有段落的代码示例:
```python
from docx import Document
def read_docx_paragraphs(file_path):
document = Document(file_path) # 打开指定路径下的 .docx 文件
paragraphs_text = [] # 存储段落文本
for paragraph in document.paragraphs: # 遍历文档中的每一个段落对象
paragraphs_text.append(paragraph.text) # 提取段落文字并存储到列表中
return paragraphs_text # 返回包含所有段落文本的列表
```
上述函数会返回一个字符串列表,其中每个元素代表文档中的一个段落[^3]。
---
#### 进阶功能:读取表格内容
除了段落外,`.docx` 文件可能还包含表格。可以通过如下方式提取表格内的数据:
```python
def read_docx_tables(file_path):
document = Document(file_path)
tables_data = []
for table in document.tables: # 遍历文档中的所有表格
rows_data = []
for row in table.rows: # 遍历当前表格的每一行
cells_data = [cell.text.strip() for cell in row.cells] # 获取单元格的内容
rows_data.append(cells_data)
tables_data.append(rows_data) # 将每张表的数据存入总列表中
return tables_data # 返回嵌套列表形式的表格数据
```
此函数能够逐个解析文档中的表格,并将它们转化为二维数组的形式。
---
#### 特殊部分:读取页眉和页脚
对于某些复杂需求,比如获取文档的页眉或页脚信息,可按照下面的方式实现:
```python
def read_headers_footers(file_path):
document = Document(file_path)
headers, footers = [], []
for section in document.sections: # 遍历文档的所有节 (Section)
header = section.header # 获得当前节的页眉对象
footer = section.footer # 获得当前节的页脚对象
if header.paragraphs: # 如果存在页眉段落
headers.extend([p.text for p in header.paragraphs])
if footer.paragraphs: # 如果存在页脚段落
footers.extend([p.text for p in footer.paragraphs])
return headers, footers # 返回页眉和页脚的文字内容
```
这段代码展示了如何访问不同章节 (`Sections`) 的页眉与页脚,并从中抽取所需的信息[^4]。
---
#### 综合应用实例
假设有一个名为 `example.docx` 的 Word 文档,我们希望一次性打印其所有的段落、表格以及页眉页脚内容:
```python
if __name__ == "__main__":
file_path = "example.docx"
# 输出段落内容
paragraphs = read_docx_paragraphs(file_path)
print("Paragraphs:", "\n".join(paragraphs))
# 输出表格内容
tables = read_docx_tables(file_path)
print("\nTables:")
for idx, table in enumerate(tables, start=1):
print(f"Table {idx}:\n{table}")
# 输出页眉页脚内容
headers, footers = read_headers_footers(file_path)
print("\nHeaders:", headers)
print("Footers:", footers)
```
以上程序综合运用了前面介绍的各种技术来全面分析目标 `.docx` 文件[^2]。
---
阅读全文
相关推荐


















