大规模编辑文档文档而不更改原始格式
编辑Word文档毫不费力,而不更改文档的原始格式。
原始DOCX库很棒,但缺少一个重要功能:保持原始格式。
但是,如果您想自动化文档编写或编辑并需要遵守严格的格式规则,则此功能非常有用。例如,这是公司环境中的普遍要求。
该模块添加了该功能,并具有一些允许编辑文档而无需更改原始格式的功能。
安装
使用PIP:PIP安装docxedit
依赖性
包括作为依赖性:python-docx(DOCX)
功能
该模块中的大多数功能主要与运行效果一起工作,这些功能是具有相同格式样式的字符串序列。将文档分解为运行,使我们能够编辑文本而无需更改原始格式。
该模块包含的一些功能:
- 用新字符串替换字符串的所有出现(可选将其限制为段落号,并包括或排除表)
- 删除包含特定字符串的行
- 将文本添加到表
该模块的优点在于,您可以使用其所有功能以一致性和精确度来质量编辑Word文档。这在可以自动化的许多文档编写或编辑可以自动化的公司环境中很有用。
如何使用
使用此模块真的很简单。这里有一些例子:
docxedit
document = Document(\’path/to/your/document.docx\’)
# Replace all instances of the word \’Hello\’ in the document with \’Goodbye\’ (including tables)
docxedit .replace_string(document, old_string=\’Hello\’, new_string=\’Goodbye\’)
# Replace all instances of the word \’Hello\’ in the document with \’Goodbye\’ but only
# up to paragraph 10
docxedit .replace_string_up_to_paragraph(document, old_string=\’Hello\’, new_string=\’Goodbye\’,
paragraph_number=10)
# Remove any line that contains the word \’Hello\’ along with the next 5 lines after that
docxedit .remove_lines(document, first_line=\’Hello\’, number_of_lines=5)
# Add text in a table cell (row 1, column 1) in the first table in the document
docxedit .add_text_in_table(document.tables[0], row_num=1, column_num=1, new_string=\’Hello\’)
# Save the document
document.save(\’path/to/your/edited/document.docx\’)\”>
from docx import Document import docxedit document = Document ( \'path/to/your/document.docx\' ) # Replace all instances of the word \'Hello\' in the document with \'Goodbye\' (including tables) docxedit . replace_string ( document , old_string = \'Hello\' , new_string = \'Goodbye\' ) # Replace all instances of the word \'Hello\' in the document with \'Goodbye\' but only # up to paragraph 10 docxedit . replace_string_up_to_paragraph ( document , old_string = \'Hello\' , new_string = \'Goodbye\' , paragraph_number = 10 ) # Remove any line that contains the word \'Hello\' along with the next 5 lines after that docxedit . remove_lines ( document , first_line = \'Hello\' , number_of_lines = 5 ) # Add text in a table cell (row 1, column 1) in the first table in the document docxedit . add_text_in_table ( document . tables [ 0 ], row_num = 1 , column_num = 1 , new_string = \'Hello\' ) # Save the document document . save ( \'path/to/your/edited/document.docx\' )
