转换超链接

2024-10-02 00:20:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一个python函数,并将类似于[text](link)的降价格式链接转换为<;a href>;HTML中的标记。例如:

连接(线)

link("Here is the link [Social Science Illustrated](https://en.wikipedia.org/wiki/Social_Science_Illustrated) I gave you yesterday.")

"Here is the link <a href="https://en.wikipedia.org/wiki/Social_Science_Illustrated">Social Science Illustrated</a> I gave you yesterday."

我现在的代码是:

^{pr2}$

输出:

=> 'Here is the link [Social Science Illustrated] ( <a href="https://en.wikipedia.org/wiki/Social_Science_Illustrated"></a> ) I gave you yesterday.'

所以我想知道如何将[文本]部分转换成正确的位置?在


Tags: thehttpsorgyouhereiswikilink
2条回答

如果您只需要根据[text](link)语法进行转换:

def link(line):
  import re
  urls = re.compile(r'\[([^\]]*)]\(([^\)]*)\)')
  line = urls.sub(r'<a href="\2">\1</a>', line)
  return line

你不必验证链接。任何像样的浏览器都不会将其作为链接呈现。在

from re import compile, sub

def html_archor_tag(match_obj):
    return '<a href="%(link)s">%(text)s</a>' %{'text': match_obj.group(1), 'link': match_obj.group(2)}

def link(line):
    markdown_url_re = re.compile(r'\[([^\]]*)]\(([^\)]*)\)')
    result = sub(markdown_url_re, html_archor_tag, line)
    return line

有关re.sub的详细信息

相关问题 更多 >

    热门问题