标签:python python-2-7 twitter tweepy
我正在对推文进行内容分析.我正在使用tweepy返回与某些术语匹配的推文,然后将N个推文写入CSv文件进行分析.创建文件和获取数据不是问题,但是我想减少数据收集时间.目前,我正在遍历文件中的术语列表.一旦达到N(例如500条推文),它将移至下一个过滤条件.
我想将所有术语(少于400个)输入到一个变量中,并使所有结果匹配.这也可以.我无法获得的是Twitter的返回值,说明状态中匹配的术语.
class CustomStreamListener(tweepy.StreamListener):
def __init__(self, output_file, api=None):
super(CustomStreamListener, self).__init__()
self.num_tweets = 0
self.output_file = output_file
def on_status(self, status):
cleaned = status.text.replace('\'','').replace('&','').replace('>','').replace(',','').replace("\n",'')
self.num_tweets = self.num_tweets + 1
if self.num_tweets < 500:
self.output_file.write(topicName + ',' + status.user.location.encode("UTF-8") + ',' + cleaned.encode("UTF-8") + "\n")
print ("capturing tweet number " + str(self.num_tweets) + " for search term: " + topicName)
return True
else:
return False
sys.exit("terminating")
def on_error(self, status_code):
print >> sys.stderr, 'Encountered error with status code:', status_code
return True # Don't kill the stream
def on_timeout(self):
print >> sys.stderr, 'Timeout...'
return True #Don't kill the stream
with open('termList.txt', 'r') as f:
topics = [line.strip() for line in f]
for topicName in topics:
stamp = datetime.datetime.now().strftime(topicName + '-%Y-%m-%d-%H%M%S')
with open(stamp + '.csv', 'w+') as topicFile:
sapi = tweepy.streaming.Stream(auth, CustomStreamListener(topicFile))
sapi.filter(track=[topicName])
具体来说,我的问题是这个.如果track变量有多个条目,如何获得匹配的内容?我还要指出,我是python和tweepy的新手.
在此先感谢您的任何建议和帮助!
解决方法:
您可以根据匹配条件检查推文文本.就像是:
>>> a = "hello this is a tweet"
>>> terms = [ "this "]
>>> matches = []
>>> for i, term in enumerate( terms ):
... if( term in a ):
... matches.append( i )
...
>>> matches
[0]
>>>
这将为您提供与该特定推文a相匹配的所有术语.在这种情况下,这仅仅是“ this”一词.
标签:python,python-2-7,twitter,tweepy 来源: https://codeday.me/bug/20191012/1902734.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。