本文整理汇总了Python中twitter.Twitter.search方法的典型用法代码示例。如果您正苦于以下问题:Python Twitter.search方法的具体用法?Python Twitter.search怎么用?Python Twitter.search使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twitter.Twitter
的用法示例。
在下文中一共展示了Twitter.search方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: render_helprequest_list_as_html
# 需要导入模块: from twitter import Twitter [as 别名]
# 或者: from twitter.Twitter import search [as 别名]
def render_helprequest_list_as_html(helprequests):
twitter = Twitter()
twitter.search('from:rybesh')
return render_template(
'helprequests+microdata+rdfa.html',
helprequests=helprequests,
tdata=twitter.search('from:rybesh'))
示例2: render_note_list_as_html
# 需要导入模块: from twitter import Twitter [as 别名]
# 或者: from twitter.Twitter import search [as 别名]
def render_note_list_as_html(notes):
twitter = Twitter()
twitter.search('from:rybesh')
return render_template(
'notes.html',
notes=notes,
tdata=twitter.search('from:rybesh'))
示例3: monitorloop
# 需要导入模块: from twitter import Twitter [as 别名]
# 或者: from twitter.Twitter import search [as 别名]
def monitorloop(self):
twitter = Twitter(domain="search.twitter.com")
results = twitter.search(q=self.query,result_type="recent",rpp="1")
watermark = results["max_id_str"]
while True:
results = twitter.search(q=self.query,result_type="recent",since_id=watermark,include_entities=1)
for tweet in results["results"]:
text = tweet["text"]
for url in tweet["entities"]["urls"]:
text = text.replace(url["url"], url["expanded_url"])
self.callback( tweet["from_user"],
"https://twitter.com/#!/" + quote(tweet["from_user"]) + "/status/" + tweet["id_str"],
text )
watermark = results["max_id_str"]
time.sleep(60)
示例4: _run
# 需要导入模块: from twitter import Twitter [as 别名]
# 或者: from twitter.Twitter import search [as 别名]
def _run(self):
iterator = None
# Display what is going to be tracked
self._animation.queue_tweet(dict(
user = dict(
screen_name = 'this_display'
),
text = "tracking \"%s\""%self._track
))
try:
if self._oauth:
twitter = Twitter(domain="search.twitter.com", auth = self._oauth)
i1 = twitter.search(q = self._track)
i1 = i1['results']
else:
i1 = None
if self._oauth:
twitter_stream = TwitterStream(auth = self._oauth)
i2 = twitter_stream.statuses.filter(track = self._track)
else:
i2 = None
iterator = chain(i1, i2)
except Exception, e:
print "Could not connect to Twitter, generating random tweets"
print "\t%s"%e
iterator = self._random()
示例5: Api
# 需要导入模块: from twitter import Twitter [as 别名]
# 或者: from twitter.Twitter import search [as 别名]
class Api(object):
def __init__(self):
self.twitter_api = None
self.twitter_search = Twitter(domain='search.twitter.com')
@twitter_error
def search(self, query, **params):
if isinstance(query, unicode):
query = query.encode('utf-8')
return self.twitter_search.search(q=query, **params)
@twitter_error
def follow(self, ids, limit=10):
" Follow on user. "
for user_id in as_tuple(ids):
self.twitter_api.friendships.create(user_id=user_id)
limit -= 1
if not limit:
return True
@twitter_error
def mentions(self, since_id=None):
" Get account mentions and save in db. "
params = dict(count=200)
if since_id:
params['since_id'] = since_id
mentions = sorted(map(
Status.create_from_status,
self.twitter_api.statuses.mentions(**params)))
db.session.add_all(mentions)
db.session.commit()
return mentions
@twitter_error
def update(self, message, async=False, **kwargs):
" Update twitter status and save it in db. "
self.app.logger.info('Tweetchi: "%s"' % message)
if not async:
status = Status.create_from_status(
self.twitter_api.statuses.update(status=message, **kwargs),
myself=True)
db.session.add(status)
db.session.commit()
return status
from .celery import update as cupdate
cupdate.delay(message,
self.config.get('OAUTH_TOKEN'),
self.config.get('OAUTH_SECRET'),
self.config.get('CONSUMER_KEY'),
self.config.get('CONSUMER_SECRET'), **kwargs)
示例6: main
# 需要导入模块: from twitter import Twitter [as 别名]
# 或者: from twitter.Twitter import search [as 别名]
def main():
conf = get_conf()
twitter = Twitter(conf)
parser = argparse.ArgumentParser()
parser.add_argument('-q', '--query', type = str,
help = "Gets all tweets and retweets for a specifc search query (realtime)")
parser.add_argument('-t', '--timeline', action = "store_true",
help = "Gets all tweets for the authenticated user")
parser.add_argument('-u', '--user', type = str,
help = "Get a timeline with a username")
parser.add_argument('-s', '--search', type = str,
help = "Get results for a search query (not realtime)")
parser.add_argument('-l', '--lookup',
help = "Get all the details for a single tweet")
parser.add_argument('-rts', '--retweetstats',
help = "Returns user info of up to 100 people that retweeted the tweet specified")
args = parser.parse_args()
if args.query:
twitter.query(args.query)
elif args.timeline:
twitter.run_timeline()
elif args.user:
twitter.user_timeline()
elif args.search:
twitter.search(args.search)
elif args.lookup:
twitter.lookup(args.lookup)
elif args.retweetstats:
sid = args.retweetstats
print("Collecting retweeters for %s" % sid)
users = twitter.retweetstats(sid)
path = "%s-retweeters.json" % sid
with open(path, "w") as f:
f.write(json.dumps(users))
print("Written retweeters to %s" % path)
else:
parser.print_help()
示例7: search
# 需要导入模块: from twitter import Twitter [as 别名]
# 或者: from twitter.Twitter import search [as 别名]
def search(keywords):
"""Search the twitter timeline for keywords"""
twitter_search = Twitter(domain="search.twitter.com")
response = twitter_search.search(q=keywords)
if response:
return response['results']
else:
return None # pragma: no cover
示例8: _scrape_twitter_for_latest
# 需要导入模块: from twitter import Twitter [as 别名]
# 或者: from twitter.Twitter import search [as 别名]
def _scrape_twitter_for_latest():
"""Scrape Twitter for interesting, new Python tips."""
# This is the secret sauce: search Twitter for '#python tip' tweets that
# are newer than our current newest.
new_tweet = Tip.query.newest_tip()
tweet_id = new_tweet.url.split('/')[-1] if new_tweet else None
twitter_search = Twitter(domain='search.twitter.com')
hits = twitter_search.search(q='#python tip', since_id=tweet_id)['results']
# And now filter out all the retweets.
not_old_rts = [t for t in hits if not _is_oldstyle_rt(t)]
embedded_tweets = [_get_embedded(t['id_str']) for t in not_old_rts]
return [t for t in embedded_tweets if not _is_newstyle_rt(t)]
示例9: main
# 需要导入模块: from twitter import Twitter [as 别名]
# 或者: from twitter.Twitter import search [as 别名]
def main():
"""Search the twitter timeline and befriend users."""
t = authenticate()
tweets = t.statuses.user_timeline()
account_user_id = t.account.verify_credentials()['id']
twitter_search = Twitter(domain="search.twitter.com")
tweets = twitter_search.search(q=SEARCH_TERMS)['results']
for tweet in tweets:
from_user_id = tweet['from_user_id']
is_following = (t.friendships.exists(user_id_a=account_user_id, user_id_b=from_user_id))
if is_following == False:
print "creating friendship between %s and %s " % (account_user_id, from_user_id)
t.friendships.create(user_id=from_user_id)
# print number of users following
friends = t.friends.ids()["ids"]
number_of_friends = len(friends)
print "You are now following %s people on twitter." % number_of_friends
示例10: retrieve_items
# 需要导入模块: from twitter import Twitter [as 别名]
# 或者: from twitter.Twitter import search [as 别名]
def retrieve_items(q, rpp=5, since_id=0):
items = Twitter.search(q, rpp, since_id)
if len(items) > 0:
Mem.set("last_tweet_id", items[0]["id"])
filtered_items = []
for item in items:
filtered_text = Twitter.clean(item["text"], q)
score = SAClient.score(filtered_text.encode("utf-8"), return_confidence=True, confidence_type=Confidence.NNP)
if score and score["confidence"] > config.NNP_CFD_THRESHOLD:
item["sentiment"] = score["score"]
print filtered_text, score["weights"]
else:
item["sentiment"] = "-"
if item["sentiment"] in set(["-", "3"]):
item["nnp"] = "neutral"
elif item["sentiment"] in set(["1", "2"]):
item["nnp"] = "negative"
elif item["sentiment"] in set(["4", "5"]):
item["nnp"] = "positive"
return items
示例11: search
# 需要导入模块: from twitter import Twitter [as 别名]
# 或者: from twitter.Twitter import search [as 别名]
def search(self, hashtag):
# search for tweets with specified hashtag
twitter_search = Twitter(domain="search.twitter.com")
return twitter_search.search(q=hashtag)
示例12: __init__
# 需要导入模块: from twitter import Twitter [as 别名]
# 或者: from twitter.Twitter import search [as 别名]
class Bot:
def __init__(self, bot):
config = ConfigParser.RawConfigParser()
config.read(os.path.dirname(__file__) + os.sep + bot + os.sep + "omni.cfg")
consumer_key = config.get(bot, 'consumer_key')
consumer_secret = config.get(bot, 'consumer_secret')
oauth = config.get(bot, 'oauth')
oauth_filename = os.path.dirname(__file__) + os.sep + bot + os.sep + oauth
oauth_token, oauth_token_secret = read_token_file(oauth_filename)
self.handle = config.get(bot, 'handle')
self.corpus = os.path.dirname(__file__) + os.sep + bot + os.sep + config.get(bot, 'corpus')
self.method = config.get(bot, 'tweet_method')
self.twitter = Twitter(domain='search.twitter.com')
self.twitter.uriparts = ()
self.poster = Twitter(
auth=OAuth(
oauth_token,
oauth_token_secret,
consumer_key,
consumer_secret
),
secure=True,
api_version='1.1',
domain='api.twitter.com')
def generate_text(self):
text = ""
with open(self.corpus) as f:
if self.method == "markov":
markov = markovgen.Markov(f)
word_count = randint(6, 18)
text = markov.generate_markov_text(size=word_count)
elif self.method == "isopsephy":
iso = isopsephy.Isopsephia(f.read())
text = iso.generate_text()
else:
lines = [line.strip() for line in f]
text = choice(lines)[:123]
return text
def tweet(self, irtsi=None, at=None):
status = self.generate_text()
if at and irtsi:
status = "@"+at+" "+status
try:
self.poster.statuses.update(
status=status,
in_reply_to_status_id=irtsi
)
except self.TwitterError:
print "Twitter Error"
else:
print status
def reply(self, mention):
asker = mention['from_user']
print asker + " said " + mention['text']
status_id = str(mention['id'])
if self.last_id_replied < status_id:
self.last_id_replied = status_id
self.tweet(status_id, asker)
def replies(self):
# get the status_id of the last tweet to which you replied
replies = [tweet['in_reply_to_status_id']
for tweet in self.poster.statuses.user_timeline()
if tweet['in_reply_to_status_id'] is not None]
try:
self.last_id_replied = replies[0]
except IndexError:
self.last_id_replied = None
results = []
results = self.twitter.search(
q="@"+self.handle,
since_id=self.last_id_replied)['results']
# do not reply to retweets
retweets = re.compile('rt\s', flags=re.I)
results = [response for response in results
if not retweets.search(response['text'])]
if not results:
print "Nobody's talking to me..."
else:
[self.reply(result) for result in results]
示例13: Twitter
# 需要导入模块: from twitter import Twitter [as 别名]
# 或者: from twitter.Twitter import search [as 别名]
from twitter import Twitter
# perform a search
twitter_search = Twitter(domain="search.twitter.com")
# Search for the latest News on #python
search = twitter_search.search(q="#python")
for tweet in search['results']:
print tweet['text']
print ''
示例14: test_search
# 需要导入模块: from twitter import Twitter [as 别名]
# 或者: from twitter.Twitter import search [as 别名]
def test_search():
t_search = Twitter(domain="search.twitter.com")
results = t_search.search(q="foo")
assert results
示例15: Twitter
# 需要导入模块: from twitter import Twitter [as 别名]
# 或者: from twitter.Twitter import search [as 别名]
#!/usr/bin/python
# coding: utf-8
from twitter import Twitter
import pickle
twitter = Twitter(domain='search.twitter.com')
query = '@kuronekounion -RT'
r = twitter.search(q=query)
next_max_id = r['max_id']
exist_count = 0
tweets = []
while(len(r['results']) != 0):
for tweet in r['results']:
next_max_id = min(next_max_id, tweet['id'] - 1)
tweets.append(tweet)
r = twitter.search(q=query, max_id=next_max_id)
tweets_file = open('tweets.pkl', 'wb')
pickle.dump(tweets, tweets_file)
tweets_file.close()