[英]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.