【问题标题】:Find strings that begins with a '#' and create link查找以“#”开头的字符串并创建链接
【发布时间】:2013-08-31 08:18:42
【问题描述】:

我想检查一个字符串(一条推文)是否以“#”开头(即是一个主题标签),如果是,则创建一个链接。

以下是我迄今为止尝试过的,但它不起作用(最后一行有错误)。 我该如何解决这个问题,代码是否能达到目的?

tag_regex = re.compile(r"""
       [\b#\w\w+]        # hashtag found!""", re.VERBOSE)

message = raw_message

for tag in tag_regex.findall(raw_message):
    message = message.replace(url, '<a href="http://statigr.am/tag/' + message[1:] + '/">' + message + '</a>')

【问题讨论】:

  • 您收到什么错误?
  • @Haidro: "赋值前引用的局部变量 'url'"
  • 您的代码中一定有更多内容,而不是您没有向我们展示的内容

标签: python regex django string hashtag


【解决方案1】:
>>> msg = '#my_tag the rest of my tweet'
>>> re.sub('^#(\w+) (.*)', r'<a href="http://statigr.am/tag/\1">\2</a>', msg)
'<a href="http://statigr.am/tag/my_tag">the rest of my tweet</a>'
>>> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-11
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    相关资源
    最近更新 更多