这里提供的答案存在一些问题。
{tag.strip("#") for tag in tags.split() if tag.startswith("#")}
[i[1:] for i in line.split() if i.startswith("#")]
如果您有像“#one#two#”这样的标签,则无法使用
2re.compile(r"#(\w+)")
不适用于许多 unicode 语言(即使使用 re.UNICODE)
我已经看到了更多提取主题标签的方法,但发现它们都没有回答所有情况
所以我写了一些小的python代码来处理大多数情况。这个对我有用。
def get_hashtagslist(string):
ret = []
s=''
hashtag = False
for char in string:
if char=='#':
hashtag = True
if s:
ret.append(s)
s=''
continue
# take only the prefix of the hastag in case contain one of this chars (like on: '#happy,but i..' it will takes only 'happy' )
if hashtag and char in [' ','.',',','(',')',':','{','}'] and s:
ret.append(s)
s=''
hashtag=False
if hashtag:
s+=char
if s:
ret.append(s)
return set(ret)