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


Python TwitterSearch类代码示例

本文整理汇总了Python中TwitterSearch的典型用法代码示例。如果您正苦于以下问题:Python TwitterSearch类的具体用法?Python TwitterSearch怎么用?Python TwitterSearch使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


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

示例1: __init__

    def __init__(self, consumer_key, consumer_secret, access_token, access_token_secret, keyword, since_id, tweet_count=15):
        self._results = []
        self._i = 0

        print("since_id: {0}".format(since_id))
        try:
            tso = TwitterSearchOrder()
            tso.set_keywords([keyword])
            tso.set_language('ja')
            tso.set_include_entities(False)
            tso.set_count(tweet_count)
            if since_id > 0:
                tso.set_since_id(long(since_id))

            ts = TwitterSearch(
                consumer_key = consumer_key,
                consumer_secret = consumer_secret,
                access_token = access_token,
                access_token_secret = access_token_secret
             )

            for tweet in ts.search_tweets_iterable(tso):
                self._results.append(
                    {
                        'screen_name': tweet['user']['screen_name'],
                        'user_name': tweet['user']['name'],
                        'profile_image_url': tweet['user']['profile_image_url'],
                        'text': tweet['text'],
                        'created_at': tweet['created_at'],
                        'id': tweet['id']
                    }
                )

        except TwitterSearchException as e:
            print(e)
开发者ID:koukomdev,项目名称:lambda_twitter_search,代码行数:35,代码来源:searchkeyword.py

示例2: jobInteraction

def jobInteraction(tag):

    tags = tag.split(",")
    tweets = []

    try:
        tso = TwitterSearchOrder()  # create a TwitterSearchOrder object
        tso.set_keywords(tags)  # let's define all words we would like to have a look for
        tso.set_language('es')  # we want to see German tweets only
        tso.set_include_entities(True)  # and don't give us all those entity information

        # it's about time to create a TwitterSearch object with our secret tokens
        ts = TwitterSearch(
            # consumer_key='QVhq5HVolTuzE79c16YDegtia',
            # consumer_secret='bfSPCAKXca52eaa2GF4a4mGceYVy4VkENwSuQtnr2c9e34TgWq',
            # access_token='1196870581-DfDo1GQQaukRZQBWn72ugdATSJqKPb4EaMsOFRK',
            # access_token_secret='tRV1lizrsCj8maKxOkzcDvp6vGJLBgDXH0ueEzmXSQTOi'
            consumer_key='gDEFFAToqZ1j5cE9SgJkeqvBY',
            consumer_secret='jqKGAra9Kd0n4jwsQXkhairyxx0uv9D4iMme6AeE2NLDX3fPfz',
            access_token='17160146-FxfSx4Bdq7SvuENSgHvi175f7uyjwoHCHVMUYiJQP',
            access_token_secret='SREyq0DxHOurUY5E0AbT3kPDwl5IFDcPFmnehZjbaH5ab'
        )

        # this is where the fun actually starts :)
        for tweet in ts.search_tweets_iterable(tso):
            # print('@%s tweeted: %s' % (tweet['user']['screen_name'], tweet['text']))
            tweets.append(tweet)

    except TwitterSearchException as e:  # take care of all those ugly errors if there are some
        print(e)

    print len(tweets)

    return json.dumps(tweets)
开发者ID:thebitisland,项目名称:business.init,代码行数:34,代码来源:api.py

示例3: get_twitters

def get_twitters():

	twitters = []
	tags = request.args.get('hashtags',False).replace('#','%23').replace('@','%40').replace(' ','').split(',')

	try:
		if len(tags)>=1:
			search_settings = TwitterSearchOrder() # create a TwitterSearchOrder object
			search_settings.set_include_entities(False) # and don't give us all those entity information
			search_settings.set_keywords( tags ) # let's define all words we would like to have a look for

			# it's about time to create a TwitterSearch object with our secret tokens
			search_on_twitter = TwitterSearch(
				consumer_key = APP_KEY,
				consumer_secret = APP_SECRET,
				access_token = OAUTH_TOKEN,
				access_token_secret = OAUTH_TOKEN_SECRET
			)
			# this is where the fun actually starsearch_on_twitter :)
			for twitter in search_on_twitter.search_tweets_iterable(search_settings):
				tw = { 'text' : twitter['text'], 'profile_image_url' : twitter['user']['profile_image_url'], 'name' : twitter['user']['name'], 'screen_name' : twitter['user']['screen_name'], 'location' : twitter['user']['location'] }
				if tw not in twitters:
					twitters.append( tw )
			# return json
			return json.dumps(twitters)
		else:
			return json.dumps([])
			
	except TwitterSearchException as e: # take care of all those ugly errors if there are some
		return json.dumps([])
开发者ID:silasvasconcelos,项目名称:tw-sort,代码行数:30,代码来源:application.py

示例4: getTweets

def getTweets(username):
    tFeeds=[]
    try:
        #tuo = TwitterUserOrder(username) # create a TwitterUserOrder
        tso = TwitterSearchOrder() # create a TwitterSearchOrder object
        tso.set_keywords([username])
        tso.set_language('en')
        tso.set_count(50)
        tso.set_include_entities(False)
        tso.set_until(date.today()-timedelta(days=2))

        # it's about time to create TwitterSearch object
        ts = TwitterSearch(
            consumer_key = '%%%',
            consumer_secret = '^^^',
            access_token = '&&&',
            access_token_secret = '@@@'
        )

        # start asking Twitter
        counter=0
        for tweet in ts.search_tweets_iterable(tso):
            if (counter==300):
                break
            tweetx=str(tweet['text'].encode('ascii', 'ignore'))
            counter=counter+1
            tFeeds.append(tweetx)
            
    except TwitterSearchException as e: # catch all those ugly errors
        print(e)
        
    return tFeeds
开发者ID:yallapragada,项目名称:social_persona,代码行数:32,代码来源:persona.py

示例5: recent_tweets

def recent_tweets(term,amt): #takes in term and
    try:
        tso = TwitterSearchOrder() # create a TwitterSearchOrder object
        tso.setKeywords(term) # let's define all words we would like to have a look for
        tso.setLanguage('en') # we want to see German tweets only
        tso.setCount(7) # please dear Mr Twitter, only give us 7 results per page
        tso.setIncludeEntities(False) # and don't give us all those entity information

        # it's about time to create a TwitterSearch object with our secret tokens
        ts = TwitterSearch(
            consumer_key = 'anOyC9WPt8qP82BkKGt34A',
            consumer_secret = 'FzAFLwXEunP34fwu3VItB3zr1P8MTOg4URuNVEI1U',
            access_token = '307461472-FZDgkwOuqLnKXYUtUaJzyJYZpFp1Nhy4IrlBURz1',
            access_token_secret = 'hoiFrBIe85VbtyMbYcxrXjbFhqUF4a6Qjolw5qbKXc'
         )

        tweet_count = 0
        at_count = 0
        hash_count = 0
        for tweet in ts.searchTweetsIterable(tso):
            for char in tweet['text']:
                if char =="@":
                    at_count +=1
                if char == "#":
                    hash_count +=1

            tweet_count+=1
            #print( '@%s tweeted: %s' % ( tweet['user']['screen_name'], tweet['text'] ) )
            if tweet_count >=amt:
                break
        #print tweet_count, at_count, hash_count
        return tweet_count, at_count, hash_count
    except TwitterSearchException as e: # take care of all those ugly errors if there are some
        #print(e)
        print "Over-exerting Twittter!! Come back in a few, you bad, bad warrior."
开发者ID:q2nev,项目名称:Twitter_Warriors,代码行数:35,代码来源:twitter.py

示例6: search_results

def search_results(words):

    #auth = OAuthHandler(keys.consumer_key, keys.consumer_secret)
    #auth.set_access_token(keys.access_token, keys.access_token_secret)

    try:

        tso = TwitterSearchOrder()
        tso.set_keywords(words)

        rilo_twitter = TwitterSearch(
            consumer_key = keys.consumer_key,
            consumer_secret = keys.consumer_secret,
            access_token = keys.access_token,
            access_token_secret = keys.access_token_secret
            )

        for tweet in rilo_twitter.search_tweets_iterable(tso):
            if  tweet['retweet_count'] > 150:
                #API.retweet(tweet['id'])
                print('@%s tweeted:  %s' % (tweet['user']['screen_name'], tweet['text']))
                print('\n\n\n')

    except TwitterSearchException as e:
        print (e)
开发者ID:belozi,项目名称:resume,代码行数:25,代码来源:twitter_app_01.py

示例7: search_twitter

def search_twitter(credentials,keywords):
    """Performs a search against the twitter search API.

        @param dict credentials     The auth credentials
        @param list keywords        The list of nkeywords to search

        @returns TwitterSearch.searchTweetsIterable()   The search results

    """

    tso = TwitterSearchOrder() # create a TwitterSearchOrder object
    tso.setKeywords(keywords) # let's define all words we would like to have a look for
    #tso.setLanguage('de') # we want to see German tweets only
    tso.setCount(100) # please dear Mr Twitter, only give us 7 results per page
    tso.setIncludeEntities(False) # and don't give us all those entity information
    #tso.setUntil(<datetime.date>)
    print tso.createSearchURL()
    # it's about time to create a TwitterSearch object with our secret tokens
    ts = TwitterSearch(
        consumer_key = credentials["tw_consumer_key"],
        consumer_secret = credentials["tw_consumer_secret"],
        access_token = credentials["tw_access_key"],
        access_token_secret = credentials["tw_access_secret"]
     )

    # for tweet in ts.searchTweetsIterable(tso):
    #     print( '@%s tweeted: %s' % ( tweet['user']['screen_name'], tweet['text'] ) )
    return ts.searchTweetsIterable(tso)
开发者ID:plablo09,项目名称:twitter_fiddles,代码行数:28,代码来源:search_twitter.py

示例8: get_new_tweets

  def get_new_tweets(self, keywords: list) -> None:
    '''
    Use the TwitterSearch lib to fetch tweets that match the given keywords.
    Pass tweets to the _store method to update the database.
    '''
    tweets = []
    if self.DEBUG: print("Searching for tweets with {} as keywords.".format(keywords)) # DEBUG
    try:
      tso = TwitterSearchOrder()
      tso.setKeywords(keywords)
      tso.setLanguage('en')
      tso.setCount(1)
      tso.setIncludeEntities(False)

      ts = TwitterSearch(
          consumer_key = 'YOUR STUFF HERE',
          consumer_secret = 'YOUR STUFF HERE',
          access_token = 'YOUR STUFF HERE',
          access_token_secret = 'YOUR STUFF HERE'
        )
      ts.authenticate()
      for tweet in ts.searchTweetsIterable(tso):
        tweets.append(tweet)
    except TwitterSearchException as e:
      self.report_error(["TwitterSearchException",e])

    if self.DEBUG: print("Fetched {} new tweets with {} as keywords.".format(len(tweets),keywords)) # DEBUG
    self._store(tweets, keywords)
开发者ID:bluechoochoo,项目名称:toots,代码行数:28,代码来源:toots.py

示例9: city_tweet

def city_tweet():
    # can't seem to get setGeocode to work via API
    try:
        tso = TwitterSearchOrder()  # create a TwitterSearchOrder object
        tso.addKeyword("RT")
        # tso.setGeocode(41.8819,87.6278,30,'km')  # let's define all words we would like to have a look for
        tso.setLanguage("en")  # we want to see German tweets only
        tso.setCount(7)  # please dear Mr Twitter, only give us 7 results per page
        tso.setIncludeEntities(False)  # and don't give us all those entity information

        # it's about time to create a TwitterSearch object with our secret tokens
        ts = TwitterSearch(
            consumer_key="anOyC9WPt8qP82BkKGt34A",
            consumer_secret="FzAFLwXEunP34fwu3VItB3zr1P8MTOg4URuNVEI1U",
            access_token="307461472-FZDgkwOuqLnKXYUtUaJzyJYZpFp1Nhy4IrlBURz1",
            access_token_secret="hoiFrBIe85VbtyMbYcxrXjbFhqUF4a6Qjolw5qbKXc",
        )

        tweet_count = 0
        at_count = 0
        hash_count = 0
        for tweet in ts.searchTweetsIterable(tso):  # this is where the fun actually starts :)
            for char in tweet["text"]:
                if char == "@":
                    at_count += 1
                if char == "#":
                    hash_count += 1
            tweet_count += 1
            # print( '@%s tweeted: %s' % ( tweet['user']['screen_name'], tweet['text'] ) )
            if tweet_count > 10:
                break
        print tweet_count, at_count, hash_count
        return tweet_count, at_count, hash_count
    except TwitterSearchException as e:  # take care of all those ugly errors if there are some
        print (e)
开发者ID:q2nev,项目名称:Twitter_Warriors,代码行数:35,代码来源:city_twitter.py

示例10: search

def search():

    tw = []
    try:
        tso = TwitterSearchOrder()  # create a TwitterSearchOrder object
        tso.set_keywords([" "])  # let's define all search keywords - now, we want all tweets with a space in them
        tso.set_language("en")  # we want to see english tweets only
        tso.set_include_entities(False)  # and don't give us all those entity information
        ts = TwitterSearch(
            consumer_key="zg9yQTGTT2oizk3XLMHGLzfpJ",
            consumer_secret="nmiwqRpWDX0oxTCUTro8sPeUVUXIZHW9O1VZcTb0mLyfHw51sc",
            access_token="700001043-oxm3LZ72y4WmWGRqY66QjV0SzZoHGy5OGgwic26M",
            access_token_secret="hGJZWTb5bjGFSiuIQrff5UajKdlyXcp7Lyun5SJzq05Su",
        )
        i = 0
        for tweet in ts.search_tweets_iterable(tso):
            # if (tweet['retweet_count'] != 0):
            # tw.append((len(tweet['text'].split()), tweet['retweet_count']))
            # print(str(i))
            # backspace(len(str(i)))
            tw.append(tweet)
            if i == 300:
                break
            i += 1
        return tw
        # print tw
        # print( '%s: @%s tweeted: %s' % ( tweet['retweet_count'], tweet['user']['screen_name'], tweet['text'] ) )
        # print # of retweents, tweeter, and content of tweet
    except TwitterSearchException as e:  # take care of all those ugly errors if there are some
        print (e)
开发者ID:Kkevsterrr,项目名称:learning_twitter,代码行数:30,代码来源:get_tweets.py

示例11: search

def search(query='cheeky nandos ledge banter', max=5):
    keywords = query.split()
    try:
        tso = TwitterSearchOrder()
        tso.set_keywords(keywords)
        # tso.set_language('en')
        # tso.set_include_entities(False)

        ts = TwitterSearch(
            consumer_key=app.config['TWITTER_CONSUMER_KEY'],
            consumer_secret=app.config['TWITTER_CONSUMER_SECRET'],
            access_token=app.config['TWITTER_ACCESS_TOKEN'],
            access_token_secret=app.config['TWITTER_TOKEN_SECRET']
        )
        results = []
        for tweet in ts.search_tweets_iterable(tso):
            results.append(tweet['id'])
            # print( '@%s tweeted: %s' % ( tweet['user']['screen_name'], tweet['text'] ) )
            max -= 1
            if not max: break
        # print results
        return results

    except TwitterSearchException as e:  # take care of all those ugly errors if there are some
        print(e)
开发者ID:madeleine789,项目名称:sius-eventboard,代码行数:25,代码来源:tweets.py

示例12: twit_search

def twit_search(keywords):
  try:
    tso = TwitterSearchOrder() # create a TwitterSearchOrder object
    tso.setKeywords(keywords) # let's define all words we would like to have a look for
    tso.setLanguage('en') # we want to see English tweets only
    tso.setCount(7) # please dear Mr Twitter, only give us 1 result per page
    tso.setIncludeEntities(False) # and don't give us all those entity information

    # it's about time to create a TwitterSearch object with our secret tokens
    ts = TwitterSearch(
        consumer_key = 'asX13sgNL5fVbVfSwyaLCw',
        consumer_secret = 'Y0SkBfcxZ5Q4AVmmXEMCcWI5lfUD3JBdgtd1fioJwU',
        access_token = '956472907-NGjoV82C6UwGu4xXLod1R3SKsWG9hfCXntt8Smxr',
        access_token_secret = '98S3jvUx5TZQxHYfBcP971ow02mTzeyQUdILamHp3Oee1'
    )

    # for tweet in ts.searchTweetsIterable(tso): # this is where the fun actually starts :)
    #    return '@%s tweeted: %s' % ( tweet['user']['screen_name'], tweet['text'] )
    tweets = []
    base_url = "https://twitter.com"
    for tweet in ts.searchTweetsIterable(tso):
      tweets.append({"screen_name": tweet['user']['screen_name'],
        "text": tweet['text'],
        "full_name": tweet['user']['name'],
        "url": "/".join([base_url, tweet['user']['screen_name'], "status", tweet['id_str']]),
        "created_at": tweet['created_at']
        })
      if len(tweets) >= 6:
        break

    return tweets

  except TwitterSearchException as e: # take care of all those ugly errors if there are some
    print(e)
    return []
开发者ID:nagoyanobakka,项目名称:newbie-coding-club,代码行数:35,代码来源:app.py

示例13: perform_search

def perform_search(request):
    """Create a page that counts hashtags"""
    tag_to_search = ""
    if request.method == "POST":
        tag_to_search = request.POST["search"]
    keyword = '"#' + tag_to_search + '"'
    users = []
    postCount = 0
    hashCount = Counter()
    uniqueHashCount = Counter()

    # Now try and talk to twitter
    try:
        tso = TwitterSearchOrder()
        tso.set_keywords([keyword])  # This is the value we search for
        tso.set_include_entities(True)  # This is to include entity information, like Hashtags

        # This is the actual search. Secrets and key's have to be obtained from twitter, and aren't to be shared.
        ts = TwitterSearch(consumer_key="xxx", consumer_secret="yyy", access_token="qqq", access_token_secret="rrr")

        # This iterates through the found tweets
        for tweet in ts.search_tweets_iterable(tso):
            # count each tweet
            postCount += 1
            # Add the organize and record the tweets for later access
            add_tweet(tweet, users)
        # now count them
        count_hashtags(hashCount, uniqueHashCount, users)
        new_id = save_data(keyword.upper(), hashCount, uniqueHashCount, postCount, len(users))
    # catch errors
    except TwitterSearchException as e:  # take care of all those ugly errors if there are some
        return str(e)

    # return that string
    return search(request, new_id)
开发者ID:nehemiahnewell,项目名称:Hashtag_Analytics,代码行数:35,代码来源:views.py

示例14: serve_twitter_news

 def serve_twitter_news(self):
     try:
         tso = TwitterSearchOrder()
         tso.set_keywords([topic])
         tso.set_language('en')
         tso.set_include_entities(False)
         
         ts = TwitterSearch(
             consumer_key = my_consumer_key,
             consumer_secret = my_consumer_secret,
             access_token = my_access_token,
             access_token_secret = my_access_token_secret
          )
          
         counter = 0
         batch_size = 5
         updates = []
         
         for tweet in ts.search_tweets_iterable(tso):
             update = '@%s: %s' % ( tweet['user']['screen_name'].encode('utf-8').strip(), tweet['text'].encode('utf-8').strip() )
             updates.append(update)
             logging.debug(update)
             counter += 1
             if counter >= batch_size:
                 self.send_JSON({ 'update' : updates })
                 break
     except TwitterSearchException as e:
         pass
开发者ID:mhausenblas,项目名称:ntil,代码行数:28,代码来源:ntil-server.py

示例15: retrieveTweets

def retrieveTweets(keyword):
    try:
        tso = TwitterSearchOrder()
        tso.set_keywords([keyword])
        tso.set_language('en')
        tso.set_include_entities(False)
        ts = TwitterSearch(
            consumer_key = 'dxDoYB875ZUsvgPtp8EVDkyq6',
            consumer_secret = '6v4GiG1B3zKmJOsYPEtb0b39lv9da7iu7pIdAANyIoisoNrtZY',
            access_token = '2157789854-Fwr0uDJQ23twqSyxPEH0VnPwafQvpay8K2z7aFQ',
            access_token_secret = 'q9S6ECBpBv1RMBG8iNT8cYdoJvQAoIMZfMHAivs5Fh0PQ')

        htmlstring = ""
        print "lolpls"

        i = 0
        for tweet in ts.search_tweets_iterable(tso):
            htmlstring += "<div><strong><a href='http://twitter.com/%s'>@%s</a></strong> %s" % (tweet['user']['screen_name'], tweet['user']['screen_name'], tweet['text']) + '</div>'

            i += 1
            if i > 1:
                break

    except TwitterSearchException as e:
        print(e)

    return htmlstring
开发者ID:AndrewLikesFood,项目名称:InBrief,代码行数:27,代码来源:RetrieveTweets.py


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