从 Python 中的字符串列表中的每个字符串中提取主题标签

Extracting hashtags from each string in a list of strings in Python

Python 菜鸟在这里。 (全面披露)

我有一个推文列表,其格式为字符串列表,如下所示:

["This is a string that needs processing #ugh #yikes",
"this string doesn't have hashtags",
"this is another one #hooray"]

我正在尝试编写一个函数,该函数将在每一行中创建主题标签列表,但在没有任何条目时保留空白条目。这是因为我想稍后将推文本身加入此列表。这是我想要的输出:

['#ugh', '#yikes'], [], ['#hooray']

我发现的这个函数 here 适用于一个字符串。

 mystring = "I love #Whosebug because #people are very #helpful!"

但它似乎不适用于多个字符串。这是我的代码:

 l = len(mystringlist)
 it = iter(mystringlist)

 taglist = []

 def extract_tags(it,l):
      for item in mystringlist:
         output = list([re.sub(r"(\W+)$", "", j) for j in list([i for i in 
         item.split() if i.startswith("#")])])
    taglist.append(output)

 multioutput = extract_tags(mystringlist,l)

 print(multioutput)

您可以使用正则表达式和 re.findall

#\w+ 将匹配后跟任何单词字符的主题标签,相当于 [a-zA-Z0-9_]

x = ["This is a string that needs processing #ugh #yikes",
"this string doesn't have hashtags",
"this is another one #hooray"]

import re

hashtags = [re.findall('#\w+', i) for i in x]
print(hashtags)

输出:

[['#ugh', '#yikes'], [], ['#hooray']]

如果正则表达式匹配任何内容,将返回一个空列表,正如您期望的输出那样。

如果您的文本可能包含 urls,例如 www.mysite.com/#/dashboard,您可以使用:

[\s^](#\w+)

确保主题标签位于空格之后或行首。

对于手头的任务,这可能被认为不可读或矫枉过正,但避免使用正则表达式,因此应该会更快一些:

>>> def hashtags(tweet):
....    return list(filter(lambda token: token.startswith('#'), tweet.split()))

>>> [hashtags(tweet) for tweet in tweets]
[['#ugh', '#yikes'], [], ['#hooray']]