我正在使用 python-docx 来操作 word 文档。这是我目前必须修改普通段落中的文本:
doc = Document('idk.docx')
for paragraph in doc.paragraphs:
if "oldtext1" in paragraph.text:
paragraph.replace("oldtext1","Something")
if "oldtext2" in paragraph.text:
paragraph.replace("oldtext2","Somethingelse")
如果我想修改表格中的文字,需要做如下操作
tables = doc.tables
for table in tables:
for row in table.rows:
for cell in row.cells:
for paragraph in cell.paragraphs:
if "oldtext1" in paragraph.text:
paragraph.replace("oldtext1","Something")
if "oldtext2" in paragraph.text:
paragraph.replace("oldtext2","Somethingelse")
代码工作正常,文本被替换,但问题是我试图替换文档中文本的所有实例,我不想有 2 个单独的循环(1 个用于段落中的普通文本,另一个用于表格中的文字)
有没有一种简单的方法可以组合这些循环,这样我就不必在 2 个不同的循环中使用相同的 if 语句?
最佳答案
我只想使用生成器理解:
from itertools import chain
for paragraph in chain(doc.paragraphs, (paragraph for table in doc.tables for row in table.rows for cell in row.cells for paragraph in cell.paragraphs)):
paragraph.replace("oldtext1","Something")
paragraph.replace("oldtext2","Somethingelse")
请注意,您不需要对 paragraph.replace()
关于Python 组合 For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36024022/