我的网站上有一些内容,其中某些关键字和关键短语应链接到其他内容。我不想手动将链接插入到内容中。在 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/