Python问题 - 次要挑战

时间:2009-08-19 14:27:29

标签: python regex

我想添加一个href链接到前缀为#或!的所有单词要么 @ 如果这是文本

检查#bamboo并联系@Fred re #bamboo #garden

应转换为:

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 个答案:

答案 0 :(得分:5)

我用一个匹配和一个选择“地点”的功能来做。即:

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)
相关问题