本文整理汇总了Python中twython.Twython.cursor方法的典型用法代码示例。如果您正苦于以下问题:Python Twython.cursor方法的具体用法?Python Twython.cursor怎么用?Python Twython.cursor使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twython.Twython
的用法示例。
在下文中一共展示了Twython.cursor方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: index
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import cursor [as 别名]
def index():
try:
APP_KEY = "KEY";
APP_SECRET = "SECRET";
twitter = Twython(APP_KEY, APP_SECRET, oauth_version=2)
ACCESS_TOKEN = twitter.obtain_access_token()
text = request.form['text']
twitter = Twython(APP_KEY, access_token=ACCESS_TOKEN)
search = twitter.cursor(twitter.search,q=text,count=1000)
totalSent = 0
i = 0
for result in search:
if i > 500:
break;
totalSent += TextBlob(result['text']).sentiment.polarity
i += 1
return render_template('index.html',name = "the twitter gods rated " + text, finding = str(wordOfIt(round(totalSent/i,2))),errorThing = None)
except:
return render_template('index.html',name = None, finding = None, errorThing = "There was an error with your input. Please try something else!")
示例2: __init__
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import cursor [as 别名]
class YalgaarTwitterInterface:
'''gets the data out from Twitter and caches it'''
hashtag = '#SaveTheInternet'
t = None
limit = 100 #The number of tweets we will collect
def __init__(self, hashtag = None, limit = 50):
'''
:hashtag: the hashtag for searching
'''
if hashtag:
self.hashtag = hashtag
self.limit = limit
self.t = Twython(APP_KEY, access_token=ACCESS_TOKEN)
def get_data(self):
results = self.t.cursor(self.t.search,
q = self.hashtag,
count = (self.limit + 100) #this is random
result_type = 'mixed'
)
try:
count = 0
tweets = {}
for r in results: #results is a GENERATOR!
if count >= self.limit:
break;
#filter out these tweets further
#we don't want anyone's conversations
#we don't want to snoop on someone's conversations
if r['in_reply_to_screen_name'] is not None:
continue;
else:
tweets[r['text']] = r
count = count + 1
return tweets
except Exception as e:
raise e
return False
示例3: Twython
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import cursor [as 别名]
#!/usr/bin/python2
# -*- coding: utf-8 -*-
from twython import Twython
APP_KEY = 'QkXeFkMDm6Mx75PzcDQkqg'
APP_SECRET = 'LY0tb8UM0Ye1X0Bk3Z99BsWKXd0I5zoG3A6wfiYErY'
OAUTH_TOKEN = 'Pwjotx1YyaqiVce77HFeOxWJxWvk8KgXYCLykZDL9ik'
OAUTH_TOKEN_SECRET='1893564546-biXRsHcfyqnsTu0Qnaz9rU4BxqeBT4PmFFhWBRH'
twitter = Twython(APP_KEY, APP_SECRET,
OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
search = twitter.cursor(twitter.search, q='Energiewende')
for result in search:
print result
示例4: Twython
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import cursor [as 别名]
from twython import Twython
APP_KEY = "h0rZYPs6iDq4orLJzBLJ0iFYl"
APP_SECRET = "y6A4U5QsfdIRzbbUNY493d696BmSVZdb4NPHRvPNp8jFpzduI4"
twitter = Twython(APP_KEY, APP_SECRET, oauth_version=2)
ACCESS_TOKEN = twitter.obtain_access_token()
twitter = Twython(APP_KEY, access_token = ACCESS_TOKEN)
tag = raw_input("Enter the term to search for-->")
results = twitter.cursor(twitter.search, q=tag)
target = open("TwittrSolrData.txt", 'a')
#target = open("TwittrSolrData.txt", 'a') For appending to the file
#number_of_tweets = raw_input("Enter the number of tweets that you want to collect-->")
i = 0
key = raw_input("Enter the key-->")
for result in results:
#target.write(result)
#target.write('\n')
print result
target.write(str(result[key]).encode("utf-8") + '\n')
#target.write(str(result) + '\n')
i = i+1
if (i > 4):
break
#print "File has been written to"
twitter.disconnect()
示例5: Twython
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import cursor [as 别名]
from textblob import TextBlob
from twython import Twython
APP_KEY = "KEY";
APP_SECRET = "SECRET";
twitter = Twython(APP_KEY, APP_SECRET, oauth_version=2)
ACCESS_TOKEN = twitter.obtain_access_token()
twitter = Twython(APP_KEY, access_token=ACCESS_TOKEN)
print 'Write what you want to search!'
search = twitter.cursor(twitter.search,q='obama',count=10)
totalSent = 0
i = 0
for result in search:
if i > 2:
break;
totalSent += TextBlob(result['text']).sentiment.polarity
i += 1
print str(totalSent/i)
示例6: TwythonAPITestCase
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import cursor [as 别名]
#.........这里部分代码省略.........
def test_request_should_raise_exception_with_invalid_json(self):
"""Test that Twython handles invalid JSON (though Twitter should not return it)"""
endpoint = 'statuses/show'
url = self.get_url(endpoint)
self.register_response(responses.GET, url, body='{"id: 210462857140252672}')
self.assertRaises(TwythonError, self.api.request, endpoint, params={'id': 210462857140252672})
@responses.activate
def test_request_should_handle_401(self):
"""Test that Twython raises an auth error on 401 error"""
endpoint = 'statuses/home_timeline'
url = self.get_url(endpoint)
self.register_response(responses.GET, url, body='{"errors":[{"message":"Error"}]}', status=401)
self.assertRaises(TwythonAuthError, self.api.request, endpoint)
@responses.activate
def test_request_should_handle_400_for_missing_auth_data(self):
"""Test that Twython raises an auth error on 400 error when no oauth data sent"""
endpoint = 'statuses/home_timeline'
url = self.get_url(endpoint)
self.register_response(responses.GET, url,
body='{"errors":[{"message":"Bad Authentication data"}]}', status=400)
self.assertRaises(TwythonAuthError, self.api.request, endpoint)
@responses.activate
def test_request_should_handle_400_that_is_not_auth_related(self):
"""Test that Twython raises a normal error on 400 error when unrelated to authorization"""
endpoint = 'statuses/home_timeline'
url = self.get_url(endpoint)
self.register_response(responses.GET, url,
body='{"errors":[{"message":"Bad request"}]}', status=400)
self.assertRaises(TwythonError, self.api.request, endpoint)
@responses.activate
def test_request_should_handle_rate_limit(self):
"""Test that Twython raises an rate limit error on 429"""
endpoint = 'statuses/home_timeline'
url = self.get_url(endpoint)
self.register_response(responses.GET, url,
body='{"errors":[{"message":"Rate Limit"}]}', status=429)
self.assertRaises(TwythonRateLimitError, self.api.request, endpoint)
@responses.activate
def test_get_lastfunction_header_should_return_header(self):
"""Test getting last specific header of the last API call works"""
endpoint = 'statuses/home_timeline'
url = self.get_url(endpoint)
self.register_response(responses.GET, url, adding_headers={'x-rate-limit-remaining': '37'})
self.api.get(endpoint)
value = self.api.get_lastfunction_header('x-rate-limit-remaining')
self.assertEqual('37', value)
value2 = self.api.get_lastfunction_header('does-not-exist')
self.assertIsNone(value2)
value3 = self.api.get_lastfunction_header('not-there-either', '96')
self.assertEqual('96', value3)
def test_get_lastfunction_header_should_raise_error_when_no_previous_call(self):
"""Test attempting to get a header when no API call was made raises a TwythonError"""
self.assertRaises(TwythonError, self.api.get_lastfunction_header, 'no-api-call-was-made')
@responses.activate
def test_sends_correct_accept_encoding_header(self):
"""Test that Twython accepts compressed data."""
endpoint = 'statuses/home_timeline'
url = self.get_url(endpoint)
self.register_response(responses.GET, url)
self.api.get(endpoint)
self.assertEqual(b'gzip, deflate', responses.calls[0].request.headers['Accept-Encoding'])
# Static methods
def test_construct_api_url(self):
"""Test constructing a Twitter API url works as we expect"""
url = 'https://api.twitter.com/1.1/search/tweets.json'
constructed_url = self.api.construct_api_url(url, q='#twitter')
self.assertEqual(constructed_url, 'https://api.twitter.com/1.1/search/tweets.json?q=%23twitter')
def test_encode(self):
"""Test encoding UTF-8 works"""
self.api.encode('Twython is awesome!')
def test_cursor_requires_twython_function(self):
"""Test that cursor() raises when called without a Twython function"""
def init_and_iterate_cursor(*args, **kwargs):
cursor = self.api.cursor(*args, **kwargs)
return next(cursor)
non_function = object()
non_twython_function = lambda x: x
self.assertRaises(TypeError, init_and_iterate_cursor, non_function)
self.assertRaises(TwythonError, init_and_iterate_cursor, non_twython_function)
示例7: Twython
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import cursor [as 别名]
#!/usr/bin/env python
from twython import Twython
from tokens import *
sn="ghost_0836"
twitter = Twython(app_key=APP_KEY, app_secret=APP_SECRET, oauth_token=OAUTH_TOKEN, oauth_token_secret=OAUTH_TOKEN_SECRET)
followers = twitter.cursor(twitter.get_friends_ids,screen_name = sn)
f=open(sn+".txt",'w')
i=1
users=[]
for follower in followers:
users.append(str(follower))
if i==100:
i=0
userlist=",".join(users)
#print len(users)
users=[]
results=twitter.lookup_user(user_id=userlist)
for result in results:
f.write(result['screen_name']+"\n")
f.flush()
i+=1
示例8: TweetSaver
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import cursor [as 别名]
saver = TweetSaver()
for tweet in timeline:
saver.handleTweet(tweet)
# For the search API
elif search_type == 3:
# tweet search
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
t_keep_tweets = keep_tweets
# Hi there. You are wondering if you can use more search parameters. Yes, yes you can.
# Read about them here: https://dev.twitter.com/docs/api/1.1/get/search/tweets
results = twitter.cursor(twitter.search,q=search_terms)
maxid = "x" # Do not change this
while t_keep_tweets > 100:
if maxid == "x":
# print "while loop initial search without maxid"
results = twitter.search(q=search_terms,count=100)
maxid = processTweetsSaveAPI(results) # Why is this a problem?
else:
# print "while loop paginated search maxid:",maxid
results = twitter.search(q=search_terms,max_id=maxid,count=100)
maxid = processTweetsSaveAPI(results)
t_keep_tweets -= 100
if t_keep_tweets <= 100:
示例9: Twython
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import cursor [as 别名]
from twython import Twython
consumer_key = "G8v4IHt7misK6qliT5eH3p1Rp"
consumer_secret = "uw3O4u9GXTdS53aS9KEDuSsdbiOLV0kN7MK3H7ZpawbM7yWHh5"
access_token_key = "22895708-O5NdDSJRKxtuTIWrAGxpNaWPKUHG1CTj8QJbjjilS"
access_token_secret = "sx2KjzCWxPCDOmQhe4cQrYQpT3Y6w0algyBcUaKzMBZXt"
twitter = Twython(
app_key=consumer_key,
app_secret=consumer_secret,
oauth_token=access_token_key,
oauth_token_secret=access_token_secret,
)
print "twitter: {}".format(twitter)
results = twitter.cursor(twitter.search, q="#python")
for result in results:
print result
break
示例10: Twython
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import cursor [as 别名]
from twython import Twython
statuses ={}
import config as c
twitter = Twython(c.CONSUMER_KEY,c.CONSUMER_SECRET,
c.ACCESS_TOKEN,c.ACCESS_SECRET)
results = twitter.cursor(twitter.search, q='python',count=10)
print results[statuses]
示例11: TwythonAPITestCase
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import cursor [as 别名]
class TwythonAPITestCase(unittest.TestCase):
def setUp(self):
client_args = {
'headers': {
'User-Agent': '__twython__ Test'
},
'allow_redirects': False
}
oauth2_client_args = {
'headers': {} # This is so we can hit coverage that Twython sets User-Agent for us if none is supplied
}
self.api = Twython(app_key, app_secret,
oauth_token, oauth_token_secret,
client_args=client_args)
self.oauth2_api = Twython(app_key, access_token=access_token,
client_args=oauth2_client_args)
def test_construct_api_url(self):
"""Test constructing a Twitter API url works as we expect"""
url = 'https://api.twitter.com/1.1/search/tweets.json'
constructed_url = self.api.construct_api_url(url, q='#twitter')
self.assertEqual(constructed_url, 'https://api.twitter.com/1.1/search/tweets.json?q=%23twitter')
def test_get(self):
"""Test Twython generic GET request works"""
self.api.get('account/verify_credentials')
def test_post(self):
"""Test Twython generic POST request works, with a full url and
with just an endpoint"""
update_url = 'https://api.twitter.com/1.1/statuses/update.json'
status = self.api.post(update_url, params={'status': 'I love Twython! %s' % int(time.time())})
self.api.post('statuses/destroy/%s' % status['id_str'])
def test_get_lastfunction_header(self):
"""Test getting last specific header of the last API call works"""
self.api.get('statuses/home_timeline')
self.api.get_lastfunction_header('x-rate-limit-remaining')
def test_get_lastfunction_header_not_present(self):
"""Test getting specific header that does not exist from the last call returns None"""
self.api.get('statuses/home_timeline')
header = self.api.get_lastfunction_header('does-not-exist')
self.assertEqual(header, None)
def test_get_lastfunction_header_no_last_api_call(self):
"""Test attempting to get a header when no API call was made raises a TwythonError"""
self.assertRaises(TwythonError, self.api.get_lastfunction_header,
'no-api-call-was-made')
def test_cursor(self):
"""Test looping through the generator results works, at least once that is"""
search = self.api.cursor(self.api.search, q='twitter', count=1)
counter = 0
while counter < 2:
counter += 1
result = next(search)
new_id_str = int(result['id_str'])
if counter == 1:
prev_id_str = new_id_str
time.sleep(1) # Give time for another tweet to come into search
if counter == 2:
self.assertTrue(new_id_str > prev_id_str)
def test_encode(self):
"""Test encoding UTF-8 works"""
self.api.encode('Twython is awesome!')
def test_html_for_tweet(self):
"""Test HTML for Tweet returns what we want"""
tweet_text = self.api.html_for_tweet(test_tweet_object)
self.assertEqual(test_tweet_html, tweet_text)
def test_html_for_tweet_expanded_url(self):
"""Test using expanded url in HTML for Tweet displays full urls"""
tweet_text = self.api.html_for_tweet(test_tweet_object,
use_expanded_url=True)
# Make sure full url is in HTML
self.assertTrue('http://google.com' in tweet_text)
def test_html_for_tweet_short_url(self):
"""Test using expanded url in HTML for Tweet displays full urls"""
tweet_text = self.api.html_for_tweet(test_tweet_object, False)
# Make sure HTML doesn't contain the display OR exapanded url
self.assertTrue(not 'http://google.com' in tweet_text)
self.assertTrue(not 'google.com' in tweet_text)
def test_raise_error_on_bad_ssl_cert(self):
"""Test TwythonError is raised by a RequestException when an actual HTTP happens"""
self.assertRaises(TwythonError, self.api.get, 'https://example.com')
# Timelines
def test_get_mentions_timeline(self):
"""Test returning mentions timeline for authenticated user succeeds"""
self.api.get_mentions_timeline()
#.........这里部分代码省略.........