Python: 从包含标签的字符串创建列表

Python: creating a list from a string containing tags

如果我有一个包含格式为 <@tag> 的标签的字符串,例如:

text = "In this test I tag <@bill>, <@Jennifer>, and lastly <@bob>."

我怎样才能得到一个 python 提取的标签列表,以便遍历标签。

['bill','Jennifer','bob']

虽然这将专门应用于我正在使用的 Slack Chatops Bot,但我将其保留为通用的,因为它可能对其他事情有用。而且我没能找到合适的 google 搜索来解决它,Stack Exchange 中建议的问题还没有涉及到这个问题..

谢谢! 尼克

您可以使用正则表达式:

import re
text = "In this test I tag <@bill>, <@Jennifer>, and lastly <@bob>."
print(re.findall('<@(.+?)>', text))  # ['bill', 'Jennifer', 'bob']

基本解释:

  • ()表示捕获组,即'extract this part for me'
  • .表示'any character'
  • .+ 表示 'any character one or more times'
  • .+? 表示 'any character one or more times, but as few as possible',否则它会包含 > 以及之后的更多字符:

print(re.findall('<@(.+)>', text)) # ['bill>, <@Jennifer>, and lastly <@bob']