python - 在文本中添加 html 超链接标记站点

标签 python html

我是 Python 新手,正在研究从纯文本到“可读”html 的转换器。 所以我几乎做了所有的事情,除了链接到很酷的超链接。

所以,我需要在文本链接中查找和替换,有一个例子:

输入:

random_text
another_random_text: https://example.com/random_text
random_text

输出:

random_text
another_random_text: <a href="https://example.com/random_text">example.com</a>
random_text

我被它困住了,不知道如何检测链接并将其正确删除

最佳答案

您可以使用正则表达式来执行任务 ( Regex101 link )。例如:

import re

s = '''
random_text
another_random_text: https://example.com/random_text
random_text
'''

s = re.sub(r'(https?://([^/]+)(?:[^\s]*))', r'<a href="\1">\2</a>', s)
print(s)

打印:

random_text
another_random_text: <a href="https://example.com/random_text">example.com</a>
random_text

关于python - 在文本中添加 html 超链接标记站点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64625687/

相关文章:

javascript - 具有固定宽度和自动调整高度的 HTML 文本输入

python - 在 QTableView 中显示某些列

javascript - 显示隐藏密码

javascript - 如何覆盖 document.body 的不透明度?

python - 在django中迭代manyToOne关系执行数百个查询

javascript - 在 html 文件中加载 Chosen.jquery.js 文件不起作用

javascript - 如何从 Django 中的模态表单更新单个字段?

python - 在python中绘制热图

python - Openstack Neutron 命令工作流程

python - 如何在本地运行 Cloud Run 服务?