【问题标题】:Convert hyperlink转换超链接
【发布时间】:2018-04-26 19:41:32
【问题描述】:

我正在尝试编写一个 python 函数并将 markdown 格式的链接(如:[text](链接))转换为 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] 部分转换为正确的位置?

【问题讨论】:

    标签: python html markdown


    【解决方案1】:

    如果只需要基于[text](link)语法进行转换:

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

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

    【讨论】:

      【解决方案2】:
      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的更多信息

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-30
        • 2015-10-23
        • 1970-01-01
        • 1970-01-01
        • 2013-06-03
        • 1970-01-01
        • 1970-01-01
        • 2011-06-28
        相关资源
        最近更新 更多