代码之家  ›  专栏  ›  技术社区  ›  PhoebeB

Python重新提问-子挑战

  •  1
  • PhoebeB  · 技术社区  · 16 年前

    我想添加一个href链接到所有前缀为#或!或@

    Check the <a href="/what/bamboo">#bamboo</a> and contact <a href="/who/fred">@Fred</a> re <a href="/what/bamboo">#bamboo</a> <a href="/what/garden">#garden</a>
    

    请注意,#和@分别指向不同的位置。

    这是我所能做的,只是做哈希。..

    matched = re.sub("[#](?P<keyword>\w+)", \
        '<a href="/what/(?P=keyword)">(?P=keyword)</a>', \
        text)
    

    任何能够为我指明正确方向的导师。我需要为每个符号进行单独的匹配吗?

    1 回复  |  直到 16 年前
        1
  •  5
  •   Alex Martelli    16 年前

    我会用一场比赛和一个选择“地点”的功能来完成。即。:

    import re
    
    places = {'#': 'what',
              '@': 'who',
              '!': 'why',
             }
    
    def replace(m):
      all = m.group(0)
      first, rest = all[0], all[1:]
      return '<a href="/%s/%s">%s</a>' % (
        places[first], rest, all)
    
    markedup = re.sub(r'[#!@]\w+', replace, text)