Python - 使用列表将数据插入word文档

Python - Insert data into a word document using a list

我有一个包含数据的 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

我认为这应该会给您想要的结果:

from docx import Document

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']

i = 0
j = 0
for para in document.paragraphs:
   if 'Keyword_one' in para.text and i < len(my_list):
      para.add_break()
      para.add_run(my_list[i])
      i += 1
   elif 'Keyword_two' in para.text and j < len(my_second_list):
      para.add_break()
      para.add_run(my_second_list[j])
      j += 1

document.save("mydocx.docx")

如果一个段落同时包含两个关键字并且您希望它从两个列表中添加,请将 elif 更改为 if