【问题标题】:Python - Insert data into a word document using a listPython - 使用列表将数据插入到 Word 文档中
【发布时间】: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


【解决方案1】:

我认为这应该会给你你正在寻找的结果:

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

【讨论】:

    猜你喜欢
    • 2012-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多