当前位置: 首页>>代码示例>>Python>>正文


Python API.user_timeline方法代码示例

本文整理汇总了Python中tweepy.API.user_timeline方法的典型用法代码示例。如果您正苦于以下问题:Python API.user_timeline方法的具体用法?Python API.user_timeline怎么用?Python API.user_timeline使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tweepy.API的用法示例。


在下文中一共展示了API.user_timeline方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: TweepyApi

# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import user_timeline [as 别名]
class TweepyApi(BaseTweepyApi, ApiAdapter):
    """
    A `ApiAdapter` implementation using `tweepy` library.

        http://github.com/tweepy/tweepy/
    """

    def __init__(self, *args, **kwargs):
        ApiAdapter.__init__(self, *args, **kwargs)

    # from `turses.api.base.ApiAdapter`

    def init_api(self):
        oauth_handler = TweepyOAuthHandler(self._consumer_key,
                                           self._consumer_secret)
        oauth_handler.set_access_token(self._access_token_key,
                                       self._access_token_secret)
        self._api = BaseTweepyApi(oauth_handler)

    @to_user
    def verify_credentials(self):
        return self._api.me()

    @to_user
    @include_entities
    def get_user(self, screen_name, **kwargs):
        return self._api.get_user(screen_name=screen_name, **kwargs)

    # timelines

    @to_status
    @include_entities
    def get_home_timeline(self, **kwargs):
        tweets = self._api.home_timeline(**kwargs)
        retweets = self._api.retweeted_to_me(**kwargs)
        tweets.extend(retweets)
        return tweets

    @to_status
    @include_entities
    def get_user_timeline(self, screen_name, **kwargs):
        return self._api.user_timeline(screen_name, **kwargs)

    @to_status
    @include_entities
    def get_own_timeline(self, **kwargs):
        me = self.verify_credentials()
        tweets = self._api.user_timeline(screen_name=me.screen_name,
                                         **kwargs)
        retweets = self._api.retweeted_by_me(**kwargs)
        tweets.extend(retweets)
        return tweets

    @to_status
    @include_entities
    def get_mentions(self, **kwargs):
        return self._api.mentions(**kwargs)

    @to_status
    @include_entities
    def get_favorites(self, **kwargs):
        return self._api.favorites(**kwargs)

    @to_direct_message
    @include_entities
    def get_direct_messages(self, **kwargs):
        dms = self._api.direct_messages(**kwargs)
        sent = self._api.sent_direct_messages(**kwargs)
        dms.extend(sent)
        return dms

    # NOTE:
    #  `get_thread` is not decorated with `to_status` because
    #  it uses `TweepyApi.get_user_timeline` which is already
    #  decorated
    @include_entities
    def get_thread(self, status, **kwargs):
        """
        Get the conversation to which `status` belongs.

        It filters the last tweets by the participanting users and
        based on mentions to each other.
        """
        author = status.authors_username
        mentioned = status.mentioned_usernames
        if author not in mentioned:
            mentioned.append(author)

        tweets = []
        for username in mentioned:
            tweets.extend(self.get_user_timeline(username, **kwargs))

        def belongs_to_conversation(status):
            for username in mentioned:
                if username in status.text:
                    return True

        return filter(belongs_to_conversation, tweets)

    @to_status_from_search
#.........这里部分代码省略.........
开发者ID:tazjel,项目名称:turses,代码行数:103,代码来源:backends.py

示例2: get_tweets

# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import user_timeline [as 别名]
def get_tweets(tweeter_id, from_id = None):
    #Setup
    #l = StdOutListener()
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = API(auth)

    #Get tweets (status) from Twitter A
    if from_id == None:
        status = api.user_timeline(user_id = tweeter_id, count=amont_of_tweets)
    else:
        status = api.user_timeline(user_id = tweeter_id, count=amont_of_tweets, max_id = from_id)
        status.pop(0) #Remove duplicate first tweet, max_id not included.

    tweetlist = []
    last_id = 0

    #print("Cleaning tweets from :", status.user.screen_name, "id: ", tweeter_id)
    for items in status:
        tweet = {}
        tweet["id"] = items.id
        tweet["user_id"] = tweeter_id
        tweet["nickname"] = items.user.screen_name
        tweet["realname"] = items.user.name
        tweet["date"] = datetime.strptime(str(items.created_at), "%Y-%m-%d %H:%M:%S")
        tweet["text"] = items.text

        tweetlist.append(tweet)
        last_id = items.id

    print("Last ID: ", last_id, "\n")
    return tweetlist, last_id
开发者ID:chrismessiah,项目名称:bachelor-thesis,代码行数:34,代码来源:twitter_mining.py

示例3: get_tweets

# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import user_timeline [as 别名]
def get_tweets(count=5):

    try:
        consumer_key = environ['TWITTER_CONSUMER_KEY']
        access_token = environ['TWITTER_ACCESS_TOKEN']
        consumer_secret = environ['TWITTER_CONSUMER_SECRET']
        access_secret = environ['TWITTER_ACCESS_SECRET']
    except KeyError:
        error("No Twitter credentials were found.")
        # We don't have login stuff, bail.
        return []

    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_secret)
    api = API(auth_handler=auth)

    try:
        statuses = api.user_timeline('pythonglasgow', count=count)
    except TweepError:
        error("Failed to read timelime.")
        return []

    tweets = [(status, twitterfy(status.text)) for status in statuses]

    return tweets
开发者ID:charliequinn,项目名称:pythonglasgow,代码行数:27,代码来源:twitter.py

示例4: FeedTwitter

# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import user_timeline [as 别名]
def FeedTwitter():
    auth = OAuthHandler(CONSUMER_KEY_TWITTER, CONSUMER_SECRET_TWITTER)
    auth.set_access_token(ACCESS_TOKEN_TWITTER, ACCESS_TOKEN_SECRET_TWITTER)
    api = API(auth)
    feed = api.user_timeline(screen_name=CONST_USER_TWITTER, count=COUNT_NUMBER_POST, page=1, include_rts=True)
    tweets = []
    for t in feed:
        if t.in_reply_to_status_id == None:
            try:
                tweet = {"text": t.text, "text_encoded": t.text, "type": "tweet", "created_time": t.created_at,
                         "link":"https://twitter.com/"+CONST_USER_LINK_TWITTER+"/status/" + str(t.id),
                         "link_encoded":urllib.quote_plus("https://twitter.com/"+CONST_USER_LINK_TWITTER+"/status/" + str(t.id)),
                         "user": {"name": t.user.name, "screen_name": "@" + t.user.screen_name,"profile_image":t.user.profile_image_url}}
                if "media" in t.entities:
                    if t.entities['media'][0]['type'] == 'photo':
                        tweet["image"] = t.entities['media'][0]['media_url']
                    else:
                        pass
                        #print t.entities['media'][0]['type']
                else:
                    pass
                    #tweet["image"] = get_randon_image()
                tweets.append(tweet)
            except Exception, e:
                #print(str(e))
                pass
开发者ID:coolirisPunk,项目名称:f12016,代码行数:28,代码来源:views.py

示例5: TweepyRateLimitTests

# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import user_timeline [as 别名]
class TweepyRateLimitTests(unittest.TestCase):

    def setUp(self):
        self.api = API(create_auth())
        self.api.retry_count = 2
        self.api.retry_delay = 5
        self.api.retry_errors = set([401, 404, 503])
        self.api.wait_on_rate_limit = True
                
    def testratelimit(self):
        # should cause the api to sleep 
        test_user_ids = [123796151, 263168076, 990027860, 901955678, 214630268, 18305040, 36126818, 312483939, 426975332, 469837158, 1104126054, 1342066705, 281632872, 608977002, 242901099, 846643308, 1166401645, 153886833, 95314037, 314458230, 149856382, 287916159, 472506496, 267180736, 251764866, 351035524, 997113991, 445915272, 57335947, 251043981, 95051918, 200761489, 48341139, 972660884, 422330517, 326429297, 864927896, 94183577, 95887514, 220807325, 194330782, 58796741, 1039212709, 1017192614, 625828008, 66539548, 320566383, 309829806, 571383983, 382694863, 439140530, 93977882, 277651636, 19984414, 502004733, 1093673143, 60014776, 469849460, 937107642, 155516395, 1272979644, 617433802, 102212981, 301228831, 805784562, 427799926, 322298054, 162197537, 554001783, 89252046, 536789199, 177807568, 805044434, 495541739, 392904916, 154656981, 291266775, 865454102, 475846642, 56910044, 55834550, 177389790, 339841061, 319614526, 954529597, 595960038, 501301480, 15679722, 938090731, 495829228, 325034224, 1041031410, 18882803, 161080540, 456245496, 636854521, 811974907, 222085372, 222306563, 422846724, 281616645, 223641862, 705786134, 1038901512, 174211339, 426795277, 370259272, 34759594, 366410456, 320577812, 757211413, 483238166, 222624369, 29425605, 456455726, 408723740, 1274608346, 295837985, 273490210, 232497444, 726843685, 465232166, 18850087, 22503721, 259629354, 414250375, 1259941938, 777167150, 1080552157, 1271036282, 1000551816, 109443357, 345781858, 45113654, 406536508, 253801866, 98836799, 395469120, 252920129, 604660035, 69124420, 283459909, 482261729, 377767308, 565240139, 191788429, 102048080, 330054371, 527868245, 177044049, 1250978114, 424042840, 15810905, 389030234, 69324415, 15638877, 159080798, 378708319, 549183840, 1034658145, 629924195, 969130340, 1143593845, 188129639, 535863656, 552452458, 1325277547, 756236624, 48421608, 178495858, 566206836, 378519925, 22678249, 377659768, 102326650, 76783997, 440716178, 49062271, 26296705, 1328036587, 289644932, 305767830, 437305735, 124821901, 591735533, 155140501, 1099612568, 631398810, 469295515, 131350941, 325804447, 529801632, 977197808, 232613818, 614777251, 229261732, 255533478, 256942503, 169583016, 237860252, 29257799, 276668845, 871571886, 398162507, 451954078, 526016951, 285655480, 1281827257, 340042172, 146653629, 61055423, 33407417, 95582321, 237420995, 310960580, 1222064886, 16490950, 60924360, 81928649, 374424010, 45703629, 817455571, 336077264, 400268024, 1203200467, 457105876, 232309205, 45838026, 91972056, 226927065, 82125276, 760131962, 1032274398, 562552291, 155155166, 146464315, 864864355, 128655844, 589747622, 293290470, 192004584, 19100402, 133931498, 19775979, 446374381, 1175241198, 20128240, 332395944, 74575955, 247407092, 427794934, 329823657, 405742072, 497475320, 997384698, 147718652, 757768705, 96757163, 289874437, 29892071, 568541704, 297039276, 356590090, 502055438, 291826323, 238944785, 71483924, 50031538, 863355416, 120273668, 224403994, 14880858, 1241506364, 848962080, 57898416, 599695908, 1222132262, 54045447, 907207212, 851412402, 454418991, 231844616, 618447410, 602997300, 447685173, 19681556, 22233657, 509901138, 184705596, 307624714, 553017923, 1249878596, 33727045, 419873350, 789307489, 287531592, 399163977, 1069425228, 920789582, 136891149, 134857296, 358558478, 436855382, 963011161, 195764827, 548872797, 1058980446, 442376799, 578216544, 527147110, 122077799, 1004773993, 420332138, 514994279, 61530732, 133462802, 19513966, 1286972018, 786121332, 265863798, 221258362, 42656382, 43631231, 198264256, 944382595, 37387030, 260948614, 314406408, 296512982, 92830743, 24519306, 21070476, 454107789, 331006606, 939713168, 256197265, 30065299, 74774188, 1332842606, 289424023, 526992024, 429933209, 116384410, 762143389, 308093598, 421208736, 454943394, 66026267, 158851748, 257550092, 70697073, 903627432, 290669225, 121168557, 92994330, 67642033, 635183794, 499303091, 421205146, 1252648171, 375268025, 16281866, 211960508, 267179466, 129016511, 157172416, 373370004, 167781059, 43624522]
        for user_id in test_user_ids:
            try:
                self.api.user_timeline(user_id=user_id, count=1, include_rts=True)
            except TweepError, e:
                # continue if we're not autherized to access the user's timeline or she doesn't exist anymore
                if e.response is not None and e.response.status in set([401, 404]): 
                    continue
                raise e
开发者ID:Aaron1011,项目名称:tweepy,代码行数:22,代码来源:test_rate_limit.py

示例6: all_tweets_from_user

# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import user_timeline [as 别名]
def all_tweets_from_user(screen_name, auth):

	api = API(auth)
	
	#initialize a list to hold all the tweepy Tweets
	alltweets = []	
	
	#make initial request for most recent tweets (200 is the maximum allowed count)
	new_tweets = api.user_timeline(screen_name = screen_name,count=200)
	
	#save most recent tweets
	alltweets.extend(new_tweets)
	
	#save the id of the oldest tweet less one
	oldest = alltweets[-1].id - 1
	
	#keep grabbing tweets until there are no tweets left to grab
	while len(new_tweets) > 0:
		print "getting tweets before %s" % (oldest)
		
		#all subsiquent requests use the max_id param to prevent duplicates
		new_tweets = api.user_timeline(screen_name = screen_name,count=200,max_id=oldest)
		
		#save most recent tweets
		alltweets.extend(new_tweets)
		
		#update the id of the oldest tweet less one
		oldest = alltweets[-1].id - 1
		
		print "...%s tweets downloaded so far" % (len(alltweets))
	
	#transform the tweepy tweets into a 2D array that will populate the csv	
	outtweets = [[tweet.id_str, tweet.created_at, tweet.text.encode("utf-8")] for tweet in alltweets]

	#write the csv	
	with open('%s_tweets.csv' % screen_name, 'wb') as f:
		writer = csv.writer(f)
		writer.writerow(["id","created_at","text"])
		writer.writerows(outtweets)
开发者ID:kownet,项目名称:osint-series,代码行数:41,代码来源:all_tweets_from_user.py

示例7: NotifyIfCachedResultTests

# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import user_timeline [as 别名]
class NotifyIfCachedResultTests(unittest.TestCase):

    def setUp(self):
        auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret)
        auth.set_access_token(oauth_token, oauth_token_secret)
        self.api = API(auth)
        self.api.retry_count = 2
        self.api.retry_delay = 5

        if not os.path.exists('cache_test_dir'):
            os.mkdir('cache_test_dir')

        self.api.cache = FileCache('cache_test_dir')
        self.api.cache.flush()

    def testhometimeline_cache(self):
        
        # no calls made, shouldnt be cached
        self.assertEqual(self.api.is_cached_result, False)

        # shouldnt be cached because we just set the cache
        self.api.home_timeline()
        self.assertEqual(self.api.is_cached_result, False)

        # Now should read from cache
        self.api.home_timeline()
        self.assertEqual(self.api.is_cached_result, True)

        # Now shouldnt read from cache, new api method call
        self.api.user_timeline('twitter')
        self.assertEqual(self.api.is_cached_result, False)

        # Now should read from cache, just made api method call
        self.api.user_timeline('twitter')
        self.assertEqual(self.api.is_cached_result, True)

        # Should still read from cache
        self.api.home_timeline()
        self.assertEqual(self.api.is_cached_result, True)
开发者ID:jsh2134,项目名称:tweepy,代码行数:41,代码来源:test_api.py

示例8: on_data

# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import user_timeline [as 别名]
    def on_data(self, data):
        print("Found something")
        try:
            decoded = json.loads(data)
        except:
            print("JSON couldn't be loaded")

        name = decoded['user']['name'].encode("utf-8", errors='ignore')
        user_id = decoded['user']['id'] #.encode("utf-8", errors='ignore')
        tweet_text = decoded['text'].encode("utf-8", errors='ignore')

        #Add number of times the user has used the search criteria in the past
        tweet_count = 0
        retweet_count = 0

        try:
            auth = AppAuthHandler(consumer_key, consumer_secret)
            auth.apply_auth()
            api = API(auth)

            users_tweets = api.user_timeline(id=user_id, count="500")
            for users_tweet in users_tweets:
                if (re.search(r'flash[ ]?mob[s]?', users_tweet.text, flags=re.IGNORECASE)):
                    tweet_count = tweet_count + 1
                    #Check how many times the past tweets have been retweeted
                    retweet_count = retweet_count + len(api.retweets(id=users_tweet.id))

            #Checks how many followers this person has
            followers_count = len(api.followers_ids(id=user_id))

        except:
            print("Something went wrong when gathering more data")
            return True

        print("User ID:       ", user_id)
        print("Tweet count:   ", tweet_count)
        print("retweet_count: ", retweet_count)
        print()

        post = {"user_id": user_id,
                "tweet": tweet_text.decode(encoding='utf-8',errors='ignore'),
                "tweet_count": tweet_count,
                "retweet_count": retweet_count}

        posts.insert(post)

        return True
开发者ID:bzabinski,项目名称:FlashMobPredictor,代码行数:49,代码来源:main.py

示例9: runTest

# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import user_timeline [as 别名]
def runTest(auth, geocode):
    searchText = "flash mob OR mobs OR flashmob"
    nycGeoCode = "40.714353,-74.00597299999998,20km"

    api = API(auth)

    if geocode is True:
        tweets = api.search(searchText, geocode=nycGeoCode, lang="en", rpp="100")
    else:
        #Note: This may cause a too many requests Twitter error
        tweets = api.search(searchText, lang="en", rpp="100")

    #basically find tweets that match the search criteria
    users_list = []
    i = 0
    for tweet in tweets:
        print(i)
        i = i + 1
        name = tweet.user.name.encode("utf-8", errors='ignore')
        user_id = tweet.user.id #.encode("utf-8", errors='ignore')
        tweet_text = tweet.text.encode("utf-8", errors='ignore')

        #Ignore users we have already checked
        if (users_list.count(name)):
            continue
        else:
            users_list.append(name)

        #Add number of times the user has used the search criteria in the past
        tweet_count = 0
        retweet_count = 0
        users_tweets = api.user_timeline(id=user_id, count="500")
        for users_tweet in users_tweets:
            if (re.search(r'flash[ ]?mob[s]?', users_tweet.text, flags=re.IGNORECASE)):
                tweet_count = tweet_count + 1
                #Check how many times the past tweets have been retweeted
                retweet_count = retweet_count + len(api.retweets(id=users_tweet.id))

        #Checks how many followers this person has
        followers_count = len(api.followers_ids(id=user_id))

        print("User ID:       ", user_id)
        print("Tweet count:   ", tweet_count)
        print("retweet_count: ", retweet_count)
        print()

    return
开发者ID:bzabinski,项目名称:FlashMobPredictor,代码行数:49,代码来源:main.py

示例10: tweets

# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import user_timeline [as 别名]
    def tweets(self):
        tweets = cache.get('tweets')
        if not tweets:
            auth = OAuthHandler(self.consumer_key, self.consumer_secret)
            auth.set_access_token(self.access_token, self.access_token_secret)
            api = API(auth)

            tweets = api.user_timeline(screen_name='TrustyJohn', count=5)
            pay_load = []
            for tweet in tweets:
                tweet_json = {'text': tweet._json['text']}
                date = tweet._json['created_at']
                tweet_json['date'] = parser.parse(date)
                pay_load.append(tweet_json)
            cache.set('tweets', pay_load, 300)
            tweets = pay_load
        return tweets
开发者ID:johnshiver,项目名称:johnshiver.org,代码行数:19,代码来源:social_media_tools.py

示例11: crawler_tweets

# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import user_timeline [as 别名]
    def crawler_tweets(self):
        log.debug('crawler_tweets')

        try:
            # TODO modularity!
            account = self.db.twitter.account
            tweets = self.db.twitter.tweets
            uid = 105351466
            auth = OAuthHandler(
                TWITTER_AUTH['CONSUMER_KEY'],
                TWITTER_AUTH['CONSUMER_SECRET']
            )
            last_stored_tweet = yield tweets.find_one(
                sort=[('id', pymongo.DESCENDING)]
            )
            user_info = yield account.find_one({'id': uid})

            auth.set_access_token(
                user_info['access_token'],
                user_info['access_token_secret']
            )
            api = API(auth)
            # TODO: block!!!
            statuses = api.user_timeline(since_id=last_stored_tweet['id'])

            count = 0
            for status in statuses:
                tweet = status._json
                if tweet['id'] <= last_stored_tweet['id']:
                    continue

                tweet = twitter_api_parser(tweet)
                yield tweets.update(
                    {'id': tweet['id']}, {'$set': tweet}, upsert=True
                )
                count += 1
                log.debug('updated {}'.format(tweet['id']))

            self.write_json(data='success crawl {} tweets'.format(count))
        except:
            err = traceback.format_exc()
            log.error(err)
            self.write_json(msg=err, status=ERROR)
        finally:
            self.finish()
开发者ID:Laisky,项目名称:laishime2,代码行数:47,代码来源:tweets.py

示例12: DataStream

# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import user_timeline [as 别名]
class DataStream(StreamListener):
    def __init__(self):
        super(DataStream, self).__init__()
        self.consumer_key = os.environ['HACKCU_APP_KEY']
        self.consumer_secret = os.environ['HACKCU_KEY_SECRET']
        self.oauth_key = os.environ['HACKCU_OAUTH_TOKEN']
        self.oauth_secret = os.environ['HACKCU_OAUTH_SECRET']
        self.auth = OAuthHandler(self.consumer_key, self.consumer_secret)
        self.auth.set_access_token(self.oauth_key, self.oauth_secret)
        self.api = API(self.auth)

    def get_home_timeline(self):
        tweet = self.api.user_timeline(id='709091333969870851', count=1, include_rts=True)
        status = tweet[0]
        json_string = json.dumps(status._json)
        json_string = json.loads(json_string)
        print json_string["text"]
        return json_string["text"]
开发者ID:FredLoh,项目名称:Chat-Bot,代码行数:20,代码来源:TwitterDataPuller.py

示例13: open

# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import user_timeline [as 别名]
from tweepy import API
from unidecode import unidecode
import json

#Variables that contain the user credentials to access Twitter API 
access_token = "ENTER TOKEN HERE"
access_token_secret = "ENTER TOKEN HERE"
consumer_key = "ENTER TOKEN HERE"
consumer_secret = "ENTER TOKEN HERE"

if __name__ == '__main__':
	
	keywordsArray = []
	keywordsPath = "keywords.txt"
	with open(keywordsPath, "r") as f:
		for keywordLine in f:
			keywordsArray.append(unidecode(keywordLine.strip()))
	
	#print keywordsArray
	#This handles Twitter authetification
	auth = OAuthHandler(consumer_key, consumer_secret)
	auth.set_access_token(access_token, access_token_secret)
	api = API(auth_handler=auth, wait_on_rate_limit=True)
	#need to use the API.user_timeline(user_id, count) method
	screenName = "NAFISZ"
	public_tweets = api.user_timeline(screen_name=screenName, count=100)
	
	for tweet in public_tweets:
		filename = ("usertweets.txt")
		with open(filename, "a") as f:
			f.write(json.dumps(tweet._json).encode('utf8') + "\n\n")
开发者ID:cvhooper22,项目名称:cs478TwitterGroup,代码行数:33,代码来源:twitUserApi.py

示例14: ExcelWriter

# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import user_timeline [as 别名]
writer = ExcelWriter('c:\\temp\\heyo.xlsx')
d = path.dirname(__file__)
consumer_key = ''
consumer_secret=''
access_token=''
access_token_secret=''
def grey_color_func(word, font_size, position, orientation, random_state=None, **kwargs):
    return "hsl(0, 0%%, %d%%)" % random.randint(60, 100)
MAX_TWEETS=5000
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = API(auth, wait_on_rate_limit=True)
screen_name='realDonaldTrump'


data = api.user_timeline(screen_name ,count=5000)

tweet_data = []

current_working_dir = "./"
log_tweets = current_working_dir  + str(time.time()) + 'tweets.txt'
with open(log_tweets, 'w') as outfile:
                for tweet in data:
                                tweet_data.append(json.loads(json.dumps(tweet._json)))
                                outfile.write(json.dumps(tweet._json))
                                outfile.write("\n")

                                              
tweets = pd.DataFrame()
#Content
#tweets['text'] = map(lambda tweet: tweet['text'].decode('utf-8',errors='ignore'), tweet_data)#Having Trouble Decoding
开发者ID:packagedjack,项目名称:Python,代码行数:33,代码来源:Tweety.py

示例15: tweets_by_user

# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import user_timeline [as 别名]
def tweets_by_user(request):
    user = request.POST.get('key')
    limit = int(request.POST.get('limit'))

    histogram_data = [['Sentiment']]
    pie_chart = [['Sentiment', 'Value'], 
                ['Neutral', 0],
                ['Positive', 0],
                ['Negative', 0]]
    statistics = {}
    tweets = []

    #Twitter Data
    api = API(auth)

    try:
        tweet_data = api.user_timeline(screen_name = user, count=limit, include_rts=False, exclude_replies=True)
    except error.TweepError:
        return render(request, 'front.html', {'username_error': 'true', 'keyword_error': 'false'})

    for tweet in tweet_data:
        text = tweet.text
        id = tweet.id
        favorite_count = tweet.favorite_count
        retweet_count = tweet.retweet_count
        blob = TextBlob(text)
        sentiment = blob.sentiment.polarity
        
        #Histogram
        histogram_data.append([blob.sentiment.polarity])

        #Statistics
        statistics[id] = sentiment
        
        #Table
        tweets.append({
            'sentiment': float("{0:.2f}".format(sentiment)),
            'text': text + ' <a href="https://twitter.com/statuses/' + 
                            str(tweet.id) + '"target="_blank">View</a>',
            'favorite_count': favorite_count,
            'retweet_count': retweet_count
            })

        #Piechart
        if sentiment == 0:
            pie_chart[1][1] += 1
        elif sentiment > 0:
            pie_chart[2][1] += 1
        elif sentiment < 0:
            pie_chart[3][1] += 1

    #Context Data
    data = {
        'user': user,
        'limit': len(tweets),
        'histogram_data': histogram_data,
        'pie_chart': pie_chart,
        'tweets': json.dumps(tweets),
        'average': float("{0:.5f}".format(average(statistics.values()))),
        'median': float("{0:.5f}".format(median(statistics.values()))),
        'std': float("{0:.5f}".format(std(statistics.values()))),
        'min': float("{0:.5f}".format(min(statistics.values()))),
        'max': float("{0:.5f}".format(max(statistics.values()))),
        'min_tweet_id': min(statistics, key=statistics.get),
        'max_tweet_id': max(statistics, key=statistics.get),
    }
    return render(request, 'dashboard-user.html', data)
开发者ID:aaaronlopez,项目名称:Social-Analytics,代码行数:69,代码来源:views.py


注:本文中的tweepy.API.user_timeline方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。