我是 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/