【问题标题】:Python how to replace a word with a hyperlink in MS Word using docx?Python如何使用docx在MS Word中用超链接替换单词?
【发布时间】:2020-08-22 10:18:58
【问题描述】:

我想用超链接替换段落中的一个单词。我看到了可以用超链接创建一个新单词的函数,但这不是我想要的。例如我想做这样的事情:

mydoc = docx.Document()
text = "a stackoverflow question"
parag = mydoc.add_paragraph(text)
parag.add_hyperlink(the word that will be changed to the hyperlink (in that case
                    that can be "stackoverflow"), link('https://stackoverflow.com'))

对于这个add_hyperlink 函数,stackoverflow 词必须是超链接。 有没有办法做到这一点?

【问题讨论】:

  • 您可以按照@scanny here提出的解决方案进行操作!
  • 它不起作用,它需要字符串,但我的是超链接,所以我收到了这个错误TypeError: 'in <string>' requires string as left operand, not CT_R

标签: python ms-word docx python-docx


【解决方案1】:

逐段构建段落,类似于:

document = docx.Document()
paragraph = mydoc.add_paragraph()
paragraph.add_run("a ")
paragraph.add_hyperlink("stackoverflow", link('https://stackoverflow.com'))
paragraph.add_run("question")

超链接必须单独出现,所以如果你想把它放在句子的中间,你需要在前后单独运行。

【讨论】:

  • 这行得通,但有点不同。添加后,当我运行我的脚本时,每次我重新启动程序时它都会开始覆盖旧文件。然后我删除了这些行,但问题仍然存在。我很困惑,除了你写的代码,我几乎什么都没有改变。
  • 即使在该代码中,它也会覆盖旧文件。在我不知道发生了什么之前,这并没有发生。你有什么主意吗? import docxmyfile = docx.Document()parag = myfile.add_paragraph('test')myfile.save('myfile.docx')
猜你喜欢
  • 2021-06-25
  • 1970-01-01
  • 1970-01-01
  • 2014-07-15
  • 2021-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多