python - 使用 Python 将 HTML 中的短语转换为链接

标签 python html regex replace

我的网站上有一些内容,其中某些关键字和关键短语应链接到其他内容。我不想手动将链接插入到内容中。在 Python 中执行此操作的最佳方法是什么(最好不使用任何 DOM 库)?

例如,我有这样的文字:

...And this can be accomplished with the Awesome Method. Blah blah blah....

Key-phrase: awesome method

这是所需的输出:

...And this can be accomplished with the <a href="/path/to/awesome-method">Awesome Method</a>. Blah blah blah....

我有一个此类关键短语和相应 URL 的列表。这些短语可以以任何大小写形式出现在内容中,但在关键短语定义中全部为小写。

目前我正在使用字符串查找替换以及大小写更改的单词的组合。而且效率相当低。

最佳答案

像这样的东西怎么样

for keyphrase, url in links:
    content = re.sub('(%s)' % keyphrase, r'<a href="%s">\1</a>' % url, content, flags=re.IGNORECASE)

例如,在您的示例中您可以这样做

import re

content = "...And this can be accomplished with the Awesome Method. Blah blah blah...."
links = [('awesome method', '/path/to/awesome-method')]

for keyphrase, url in links:
    content = re.sub('(%s)' % keyphrase, r'<a href="%s">\1</a>' % url, content, flags=re.IGNORECASE)

# content:
# '...And this can be accomplished with the <a href="/path/to/awesome-method">Awesome Method</a>. Blah blah blah....'

关于python - 使用 Python 将 HTML 中的短语转换为链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32063539/

相关文章:

python - tensorflow cnn 错误 : InvalidArgumentError (see above for traceback): logits and labels must be same size

html - Css 选择所有但第一个 tr 不起作用

html - Bootstrap - 无法居中 div

regex - "grep -v ' ^ $' file.txt"在做什么?

Python 正则表达式 : exclude\r\n

python - 将列表中的每三个项目组合在一起 - Python

python - 如何使用 ctypes 将 void * 来回传递给 python 中的共享库?

python - 属性错误 : 'tuple' object has no attribute 'drivername' using Flask SqlAlchemy

html - 所选文本显示过大的选择区域

Java:在两个不同的点将一个字符串拆分为 3 个部分