【问题标题】:Extracting hashtags from each string in a list of strings in Python从 Python 中的字符串列表中的每个字符串中提取主题标签
【发布时间】:2018-10-07 20:22:40
【问题描述】:

这里是 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 #stackoverflow 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)

【问题讨论】:

    标签: python arrays list pandas data-cleaning


    【解决方案1】:

    您可以使用正则表达式和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+)

    确保在空格之后或行首找到主题标签。

    【讨论】:

      【解决方案2】:

      这对于手头的任务可能被认为是不可读或过度杀伤力,但避免使用正则表达式,因此应该更快:

      >>> def hashtags(tweet):
      ....    return list(filter(lambda token: token.startswith('#'), tweet.split()))
      
      >>> [hashtags(tweet) for tweet in tweets]
      [['#ugh', '#yikes'], [], ['#hooray']]
      

      【讨论】:

      • In [9]: %timeit [hashtags(tweet) for tweet in tweets] 6.72 µs ± 28.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
      • In [10]: %timeit [re.findall('#\w+', i) for i in tweets] 3.4 µs ± 59.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
      • 是否可以重新设计它,使其全部在 def() 函数内部运行? (出于模块化目的)
      猜你喜欢
      • 2012-06-15
      • 2021-07-30
      • 1970-01-01
      • 1970-01-01
      • 2023-01-16
      • 2018-12-13
      • 1970-01-01
      • 2017-12-15
      • 1970-01-01
      相关资源
      最近更新 更多