如何用Python / Django中的HTML Anchor替换Hashtags?

时间:2014-10-27 11:06:27

标签: python regex django

message = "@me this is nice. @you: let me #help you. #anyone> #Python, #All."

message.split()给出"

['@me', 'this', 'is', 'nice.', '@you:', 'let', 'me', '#help', 'you.', '#anyone>', '#Python,', '#All.']

但我想要的是

['@me', 'this', 'is', 'nice.', '@you', 'let', 'me', '#help', 'you.', '#anyone', '#Python', '#All']。没有:.>或任何其他符号。我只想要单词

startswith('#')应该返回

['#help', '#anyone', '#Python', #All]然后hashtag_links将返回

["<a href='hashtags\help'>#help</a>", "<a href='hashtags\anyone'>#anyone</a>", ...]

我想要做的是能够将message中的主题标签替换为hashtag_links中的等效标签,以便在以HTML格式呈现时可以点击它们。

2 个答案:

答案 0 :(得分:1)

[\s.:>,]

您可以按此分割。使用re.split。删除空白组。

参见演示。

http://regex101.com/r/sU3fA2/11

答案 1 :(得分:1)

您可以使用列表推导轻松完成此任务:

mylist = [i.rstrip(":;") for i in message.split() if i] # remove blanks
hashtagged = [i for i in mylist if i.startswith("#")]