我有时间在包含主题标签的推文中获取信息,并使用Python将每个主题标签拉入数组。我甚至对我迄今为止所做的尝试感到尴尬。
例如,“我喜欢#stackoverflow,因为#people非常#helpful!”
这应该将3个主题标签拉入数组。
答案 0 :(得分:54)
一个简单的正则表达式应该可以胜任:
>>> import re
>>> s = "I love #stackoverflow because #people are very #helpful!"
>>> re.findall(r"#(\w+)", s)
['stackoverflow', 'people', 'helpful']
请注意,正如其他答案中所建议的那样,这也可能会找到非主题标签,例如网址中的哈希位置:
>>> re.findall(r"#(\w+)", "http://example.org/#comments")
['comments']
所以另一个简单的解决方案是以下(删除重复项作为奖励):
>>> 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'])
答案 1 :(得分:18)
>>> s="I love #stackoverflow because #people are very #helpful!"
>>> [i for i in s.split() if i.startswith("#") ]
['#stackoverflow', '#people', '#helpful!']
答案 2 :(得分:6)
AndiDogs的答案会搞砸链接和其他内容,你可能想先将它们过滤掉。之后使用此代码:
UTF_CHARS = ur'a-z0-9_\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u00ff'
TAG_EXP = ur'(^|[^0-9A-Z&/]+)(#|\uff03)([0-9A-Z_]*[A-Z_]+[%s]*)' % UTF_CHARS
TAG_REGEX = re.compile(TAG_EXP, re.UNICODE | re.IGNORECASE)
这似乎有点矫枉过正,但已经从这里转换http://github.com/mzsanford/twitter-text-java。 它将以与twitter处理它们相同的方式处理所有主题标签的99%。
有关更多转换后的twitter正则表达式,请查看:http://github.com/BonsaiDen/Atarashii/blob/master/atarashii/usr/share/pyshared/atarashii/formatter.py
答案 3 :(得分:2)
答案 4 :(得分:1)
hashtags = [word for word in tweet.split() if word[0] == "#"]
答案 5 :(得分:0)
最好的 Twitter hashtag正则表达式:
import re
text = "#promovolt #1st # promovolt #123"
re.findall(r'\B#\w*[a-zA-Z]+\w*', text)
>>> ['#promovolt', '#1st']
答案 6 :(得分:-2)
我以一种愚蠢但有效的方式提取了主题标签。
def retrive(s):
indice_t = []
tags = []
tmp_str = ''
s = s.strip()
for i in range(len(s)):
if s[i] == "#":
indice_t.append(i)
for i in range(len(indice_t)):
index = indice_t[i]
if i == len(indice_t)-1:
boundary = len(s)
else:
boundary = indice_t[i+1]
index += 1
while index < boundary:
if s[index] in "`~!@#$%^&*()-_=+[]{}|\\:;'"",.<>?/ \n\t":
tags.append(tmp_str)
tmp_str = ''
break
else:
tmp_str += s[index]
index += 1
if tmp_str != '':
tags.append(tmp_str)
return tags