我发布了这个问题(即使我在这里看到了几个相同的问题),因为(据我所知)这些问题都没有解决这个问题。我曾经尝试过使用oodocx库,但是没有用。所以我找到了一种解决方法。
代码非常相似,但是逻辑是:当我找到包含要替换的字符串的段落时,请使用 runs
添加另一个循环。(这仅在我要替换的字符串具有相同格式的情况下才有效)。
def replace_string(filename): doc = document(filename) for p in doc.paragraphs: if 'old text' in p.text: inline = p.runs # Loop added to work with runs (strings with same style) for i in range(len(inline)): if 'old text' in inline[i].text: text = inline[i].text.replace('old text', 'new text') inline[i].text = text print p.text doc.save('dest1.docx') return 1


