使用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.tablesfor 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 + bAccessing the docstringprint(add.__doc__)Using the help functionhelp(add)
以上是使用`python-docx`进行文档操作的基本方法。你可以根据需要添加更多功能,如表格、标题、样式等。希望这能帮助你开始使用Python处理Word文档!
