用Python从字符串中提取标签的一种优雅方法?

2024-03-29 09:24:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种干净的方法来获取给定字符串中以#开头的单词集(list,array,whatever)。

在C#里,我会写

var hashtags = input
    .Split (' ')
    .Where (s => s[0] == '#')
    .Select (s => s.Substring (1))
    .Distinct ();

在Python中,什么是比较优雅的代码?

编辑

示例输入:"Hey guys! #stackoverflow really #rocks #rocks #announcement"
预期输出:["stackoverflow", "rocks", "announcement"]


Tags: 方法字符串inputvarwhere单词stackoverflowarray
3条回答

regular expression objectsfindall方法可以一次获得它们:

>>> import re
>>> s = "this #is a #string with several #hashtags"
>>> pat = re.compile(r"#(\w+)")
>>> pat.findall(s)
['is', 'string', 'hashtags']
>>> 

使用@inspectorG4dget's answer时,如果不需要重复项,可以使用集合理解而不是列表理解。

>>> tags="Hey guys! #stackoverflow really #rocks #rocks #announcement"
>>> {tag.strip("#") for tag in tags.split() if tag.startswith("#")}
set(['announcement', 'rocks', 'stackoverflow'])

请注意,集合理解的{ }语法仅从Python 2.7开始工作。
如果使用的是旧版本,则将列表理解([ ])输出作为set函数。

[i[1:] for i in line.split() if i.startswith("#")]

这个版本将去掉任何空字符串(正如我在注释中读到的那样)和只有"#"的字符串。另外,在Bertrand Marron的代码中,最好将其转换为以下集合(以避免重复和O(1)查找时间):

set([i[1:] for i in line.split() if i.startswith("#")])

相关问题 更多 >