如何使用 python 更新现有 word 文档中的内容
How to update content in existing word document using python
我有以下格式的现有 word 文档。
1. Test Case Specification Identifier
[test case number] 55-01-01
[title] Login with default
[revision history]
2. Test Items
[objective]
3. Execution
[step 1] ;# Non-executable description
[step 1.1] ;# Executable Step Level 2 or more
我想打开此 word 文档并使用 python 将 [objective] 和 [step] 更新为以下值。
objective = "This is objective"
步数 = {"step1":["step1.1","step1.2"],"step2":["step2.1"]}
包含以上数据后,输出文档如下所示。
1. Test Case Specification Identifier
[test case number] 55-01-01
[title] Login with default
[revision history]
2. Test Items
[objective]
This is objective
3. Execution
[step 1] Step 1
[step 1.1] Step 1.1
[step 1.2] Step 1.2
[step 2] Step 2
[step 2.1] Step 2.1
你能帮忙吗?
试试这个:
from docx import Document
import re
document = Document(docx='existing.docx')
objective = "This is objective"
steps = ["step 1", "step 1.1", "step 1.2", "step 2", "step 2.1"]
# read current document contents
for paragraph in document.paragraphs:
if '[objective]' in paragraph.text:
paragraph.text += objective
for step in steps:
indent = 1
if re.search(r"{}\]".format(step), paragraph.text):
print step, paragraph.text
if '.' in step:
indent += 1
paragraph.text = '{}[{}]\t{}'.format('\t'*indent, step, step.title())
steps.remove(step)
# add remaining steps not in existing document
for step in steps:
indent = 1
if '.' in step:
indent += 1
document.add_paragraph('{}[{}]\t{}'.format('\t'*indent, step, step.title()))
document.save('output.docx')
我有以下格式的现有 word 文档。
1. Test Case Specification Identifier
[test case number] 55-01-01
[title] Login with default
[revision history]
2. Test Items
[objective]
3. Execution
[step 1] ;# Non-executable description
[step 1.1] ;# Executable Step Level 2 or more
我想打开此 word 文档并使用 python 将 [objective] 和 [step] 更新为以下值。
objective = "This is objective"
步数 = {"step1":["step1.1","step1.2"],"step2":["step2.1"]}
包含以上数据后,输出文档如下所示。
1. Test Case Specification Identifier
[test case number] 55-01-01
[title] Login with default
[revision history]
2. Test Items
[objective]
This is objective
3. Execution
[step 1] Step 1
[step 1.1] Step 1.1
[step 1.2] Step 1.2
[step 2] Step 2
[step 2.1] Step 2.1
你能帮忙吗?
试试这个:
from docx import Document
import re
document = Document(docx='existing.docx')
objective = "This is objective"
steps = ["step 1", "step 1.1", "step 1.2", "step 2", "step 2.1"]
# read current document contents
for paragraph in document.paragraphs:
if '[objective]' in paragraph.text:
paragraph.text += objective
for step in steps:
indent = 1
if re.search(r"{}\]".format(step), paragraph.text):
print step, paragraph.text
if '.' in step:
indent += 1
paragraph.text = '{}[{}]\t{}'.format('\t'*indent, step, step.title())
steps.remove(step)
# add remaining steps not in existing document
for step in steps:
indent = 1
if '.' in step:
indent += 1
document.add_paragraph('{}[{}]\t{}'.format('\t'*indent, step, step.title()))
document.save('output.docx')