转换超链接

时间:2017-11-14 00:51:05

标签: python html markdown

我正在尝试编写一个python函数并将markdown格式链接转换为< [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."

我现在的代码是:

def link(line):
  import re
  urls = re.compile(r"((https?):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)")
  line = urls.sub(r'<a href="\1"></a>', line)
  return line

输出:

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

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

2 个答案:

答案 0 :(得分:1)

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

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

您无需验证链接。任何体面的浏览器都不会将其作为链接呈现。

答案 1 :(得分:0)

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

的更多信息