繁体   English   中英

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")

所需示例 output:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM