我正在分析Twitter数据以进行情绪分析,我需要将推文标记为我的分析。
这是一个推文示例:
tweet = "Barça, que más veces ha jugado contra 10 en la historia https://twitter.com/7WUjZrMJah #UCL"
nltk.word_tokenize()
将推文标记为好,但会在链接和主题标签处中断。
word_tokenize(tweet)
>>> ['Bar\xc3\xa7a', ',', 'que', 'm\xc3\xa1s', 'veces', 'ha', 'jugado', 'contra', '10', 'en', 'la', 'historia', 'https', ':', '//twitter.com/7WUjZrMJah', '#', 'UCL']`
unicode字符保持不变,但链接断开。我设计了一个自定义正则表达式标记器,它是:
emoticons = r'(?:[:;=\^\-oO][\-_\.]?[\)\(\]\[\-DPOp_\^\\\/])'
regex_tweets = [
emoticons,
r'<[^>]+>', ## HTML TAGS
r'(?:@[\w\d_]+)', ## @-mentions
r'(?:\#[\w]+)', ## #HashTags
r'http[s]?://(?:[a-z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-f][0-9a-f]))+', # URLs
r"(?:[a-z][a-z'\-_]+[a-z])", # words with - and '
r'(?:(?:\d+,?)+(?:\.?\d+)?)', ##numbers
r'(?:[\w_]+)', #other words
r'(?:\S)' ## normal text
]
#compiling regex
tokens_re = re.compile(r'('+'|'.join(regex_tweets)+')' ,re.IGNORECASE | re.VERBOSE)
tokens_re.findall(string)
>>> ['Bar', '\xc3', '\xa7', 'a', ',', 'que', 'm', '\xc3', '\xa1', 's', 'veces', 'ha', 'jugado', 'contra', '10', 'en', 'la', 'historia', 'https://twitter.com/7WUjZrMJah', '#UCL']
现在,主题标签和链接以我希望的方式显示,但在unicode字符串中断开(例如Barça - &gt; ['Bar', '\xc3', '\xa7', 'a']
而不是['Bar\xc3\xa7a']
有什么方法可以整合这两个? 或者包含unicode字符的正则表达式
我还尝试了TweetTokenizer
库中的nltk.tokenize
,但它不是很有用。
答案 0 :(得分:0)
如果我将字符串声明为unicode字符串,那么大多数unicode字符都会中断。它仍然打破了许多词,但性能更好。
# coding=utf-8
tweet = u"Barça, que más veces ha jugado contra 10 en la historia https://twitter.com/7WUjZrMJah #UCL"
emoticons = r'(?:[:;=\^\-oO][\-_\.]?[\)\(\]\[\-DPOp_\^\\\/])'
regex_tweets = [
emoticons,
r'<[^>]+>', ## HTML TAGS
r'(?:@[\w\d_]+)', ## @-mentions
r'(?:\#[\w]+)', ## #HashTags
r'http[s]?://(?:[a-z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-f][0-9a-f]))+', # URLs
r"(?:[a-z][a-z'\-_]+[a-z])", # words with - and '
r'(?:(?:\d+,?)+(?:\.?\d+)?)', ##numbers
r'(?:[\w_]+)', #other words
r'(?:\S)' ## normal text
]
#compiling regex
tokens_re = re.compile(r'('+'|'.join(regex_tweets)+')' ,re.IGNORECASE | re.VERBOSE)
tokens_re.findall(string)
>>>[u'Bar', u'\xe7a', u',', u'que', u'm\xe1s', u'veces', u'ha', u'jugado', u'contra', u'10', u'en', u'la', u'historia', u'https://twitter.com/7WUjZrMJah', u'#UCL']
它仍然将Barça
标记为[u'Bar', u'\xe7a']
,这比['Bar', '\xc3', '\xa7', 'a']
更好,但仍然不是原始术语['Bar\xc3\xa7a']
。但它确实适用于许多表达方式。