如何通过twitterapi使用python格式化tweet?

2024-03-29 06:35:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我通过twitter api收集了一些tweet。然后我在python中使用split(' ')计算单词数。但是,有些词是这样出现的:

correct! 
correct.
,correct
blah"
...

那么,如何在没有标点符号的情况下格式化tweets呢?或者我应该尝试另一种方法来发tweets?谢谢。在


Tags: 方法api情况twitter单词tweetstweetsplit
3条回答

{{cd1>你可以使用多个字符来分割}。。。在

from string import punctuation
import re

puncrx = re.compile(r'[{}\s]'.format(re.escape(punctuation)))
print filter(None, puncrx.split(your_tweet))

或者,只需查找包含某些连续字符的单词:

^{pr2}$

例如:

print re.findall(r'[\w@#]+', 'talking about #python with @someone is so much fun! Is there a     140 char limit? So not cool!')
# ['talking', 'about', '#python', 'with', '@someone', 'is', 'so', 'much', 'fun', 'Is', 'there', 'a', '140', 'char', 'limit', 'So', 'not', 'cool']

我最初在这个例子中有一个笑脸,但是当然,这些笑脸最终会被这个方法过滤掉,所以这是值得警惕的。在

在进行拆分之前,请尝试从字符串中删除标点符号。在

import string
s = "Some nice sentence.  This has punctuation!"  
out = s.translate(string.maketrans("",""), string.punctuation)

然后对out执行split。在

我建议在使用以下代码拆分文本之前清除特殊符号中的文本:

tweet_object["text"] = re.sub(u'[!?@#$.,#:\u2026]', '', tweet_object["text"])

在使用函数sub之前,您需要导入re

^{pr2}$

相关问题 更多 >