【发布时间】:2021-02-06 17:29:44
【问题描述】:
我有一个包含数据的 word 文档,我有 2 个带有短语的列表。我想循环遍历 word 文档以及找到特定关键字的任何位置(在本例中为 keyword_one 和 keyword_two),添加新行并插入相关列表中的第一项。
我下面的代码只是将一个列表中的一项添加到keyword_one,我认为这可能与for循环结构有关-请有人指出我正确的方向吗?
代码:
document = Document('mydocx.docx')
my_list=['Some key points here', 'We expected values to be higher. That is fine', 'final attributes', 'local dataset']
my_second_list=['My random data', 'Flowers. That is fine', 'happy birthday', 'puppies']
for para in document.paragraphs:
print(para.text)
for i in my_list:
for j in my_second_list:
if 'Keyword_one' in para.text:
para.add_run(' ' +i)
if 'Keyword_two' in para.text:
para.add_run(' ' + j)
else:
break
document.save("mydocx.docx")
所需的示例输出:
My ms word document.
Keyword_one
Some key points here. I have some additional data
Other data here
Keyword_two
Flowers
Heading 1
Keyword_one
We expected values to be higherThat is fine'
Keyword_one
final attributes
Keyword_two
My random data. Other random data here
Heading 1
Keyword_two
Flowers
【问题讨论】:
-
澄清一下,您的意思是当第一个关键字出现时,插入第一个列表的第一项(第二个关键字也是如此) - 下次第一个关键字再次出现时,使用第一个列表的第二项,等等?当您浏览完整个列表后会发生什么?
-
没错。无论文档中是否有更多实例,它都可以在到达两个列表的最后一个元素时停止
标签: python python-3.x string list python-docx