我想添加一个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>
Run Code Online (Sandbox Code Playgroud)
请注意#和@去不同的地方.
这是我所拥有的,只是做哈希...
matched = re.sub("[#](?P<keyword>\w+)", \
'<a href="/what/(?P=keyword)">(?P=keyword)</a>', \
text)
Run Code Online (Sandbox Code Playgroud)
任何一位专家都能指出我正确的方向.我是否需要为每个符号分别进行匹配?
我会用一个匹配和一个选择"地点"的功能来做.即:
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
187 次 |
| 最近记录: |