使用Python处理Word文档,你可以使用`python-docx`库。以下是使用`python-docx`库进行文档操作的基本步骤:
安装`python-docx`库
pip install python-docx
创建文档
from docx import Document
创建一个新的文档对象
document = Document()
保存文档
document.save('test.docx')
打开现有文档
打开一个已存在的文档
document = Document('filename.docx')
保存文档
document.save('new-filename.docx')
添加段落
添加一个新的段落
paragraph = document.add_paragraph('This is the first paragraph')
在特定段落前插入另一个段落
prior_paragraph = document.add_paragraph('such a good boy')
设置样式
设置文档的基础字体和样式
document.styles['Normal'].font.name = '微软雅黑'
document.styles['Normal'].font.size = Pt(14)
设置文档的基础样式
document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), '微软雅黑')
插入图片
插入图片
document.add_picture('d:/无标题.png', width=Inches(6))
读取文档
打开一个文档
dfile = Document('demo.docx')
获取文档的核心属性
core_properties = dfile.core_properties
获取文档中的段落
for idx, paragraph in enumerate(dfile.paragraphs):
print(f'Paragraph {idx + 1}: {paragraph.text}')
获取文档中的表格
file_tb = Document('tables.docx')
tb = file_tb.tables
for table in tb:
print(table)
文档字符串
在Python中,可以使用文档字符串(docstring)为函数、类或方法提供文档说明。
def add(a, b):
"""
This function takes two numbers as input and returns their sum.
Parameters:
a (int): The first number.
b (int): The second number.
Returns:
int: The sum of the two input numbers.
"""
return a + b
Accessing the docstring
print(add.__doc__)
Using the help function
help(add)
以上是使用`python-docx`进行文档操作的基本方法。你可以根据需要添加更多功能,如表格、标题、样式等。希望这能帮助你开始使用Python处理Word文档!