Parsing a tweet to extract hashtags into an array

前端 未结 9 756
旧时难觅i
旧时难觅i 2020-12-03 05:33

I am having a heck of a time taking the information in a tweet including hashtags, and pulling each hashtag into an array using Python. I am embarrassed to even put what I

9条回答
  •  无人及你
    2020-12-03 06:12

    A simple regex should do the job:

    >>> import re
    >>> s = "I love #stackoverflow because #people are very #helpful!"
    >>> re.findall(r"#(\w+)", s)
    ['stackoverflow', 'people', 'helpful']
    

    Note though, that as suggested in other answers, this may also find non-hashtags, such as a hash location in a URL:

    >>> re.findall(r"#(\w+)", "http://example.org/#comments")
    ['comments']
    

    So another simple solution would be the following (removes duplicates as a bonus):

    >>> def extract_hash_tags(s):
    ...    return set(part[1:] for part in s.split() if part.startswith('#'))
    ...
    >>> extract_hash_tags("#test http://example.org/#comments #test")
    set(['test'])
    

提交回复
热议问题