我正在尝试获取Tweets的大型数据集,其中包含关键字“IAmsterdam”(阿姆斯特丹的城市营销活动)。 我尝试使用Twitter的流API和REST API,但是我无法获得可以分析的大型数据集(情感分类)
你们有谁知道如何获得有关IAmsterdam的更多推文?
代码REST API:
from TwitterSearch import *
import time
import sys
import codecs
#change to more convenient output type (utf-8)
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
try:
tso = TwitterSearchOrder()
tso.set_keywords(['IAmsterdam'])
tso.set_language('en')
ts = TwitterSearch(
consumer_key = '6ZnWpt6HZ1kOVSEjfFwUnLia6',
consumer_secret = .... ,
access_token = '2815625730-qSoq6TWyfzqpPJvY71DNAQwGUAfoQu23KgLcPg1',
access_token_secret = ...
)
sleep_for = 60 # sleep for 60 seconds
last_amount_of_queries = 0 # used to detect when new queries are done
for tweet in ts.search_tweets_iterable(tso):
print( '@%s tweeted: %s' % ( tweet['user']['screen_name'], tweet['text'] ) )
current_amount_of_queries = ts.get_statistics()[0]
if not last_amount_of_queries == current_amount_of_queries:
last_amount_of_queries = current_amount_of_queries
time.sleep(sleep_for)
except TwitterSearchException as e:
print(e)
代码STREAMING API
import time, sys, codecs
#Import the necessary methods from tweepy library
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
#Variables that contains the user credentials to access Twitter API
access_token = "2815625730-qSoq6TWyfzqpPJvY71DNAQwGUAfoQu23KgLcPg1"
access_token_secret = ....
consumer_key = "6ZnWpt6HZ1kOVSEjfFwUnLia6"
consumer_secret = ....
#This is a basic listener that just prints received tweets to stdout.
class StdOutListener(StreamListener):
def on_data(self, data):
try:
#print data
tweet = data.split(',"text":"')[1].split('","source')[0]
print tweet
saveThis = str('')+ tweet #saves time+actual tweet
saveFile = open('amsiams6415.txt','a')
saveFile.write(saveThis)
saveFile.write('\n')
saveFile.close()
return True
except BaseException, e:
print 'failed ondata,',str(e)
time.sleep(5)
def on_error(self, status):
print status
if __name__ == '__main__':
#This handles Twitter authetification and the connection to Twitter Streaming API
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
#This line filter Twitter Streams to capture data by the keywords: 'Amsterdam'
stream.filter(track=['IAmsterdam'], languages=['en'])
答案 0 :(得分:1)
这里不需要代码示例:)。
其余api的问题是它只提供6-9天的推文。流式api只会在发生时发送推文。因此,在这两种情况下,您都必须在更长的时间内收集数据才能获得大量数据集。
或者您必须减少搜索限制,并搜索其他主题标签/关键字。
如果您想快速构建大型数据集和/或获取历史数据,那么您可以使用类似http://topsy.com/的内容,它会让您的推文回到Twitter时间的开头。这是付费服务(还有其他服务)。
答案 1 :(得分:0)
您从API获取的数据与您使用advanced search时看到的数据相同 似乎没有多少推文使用“IAmsterdam”这个词,每小时只有几个,我可以看到,而且你通过指定lang = en使搜索更具限制性,所以你可以试试:
此外,我建议您更改授权令牌,因为虽然您已删除了这些令牌,但仍有足够的时间让某人复制或存储在网络搜索缓存中。