Twitter API:由用户提取推文并使用Twython(Python)包含关键字

时间:2017-02-13 01:16:39

标签: python api twitter twython

我是Python和Twython的新手,可以使用#3的一些帮助。我正在进行一些研究,并希望由用户提取推文并包含某个关键字。我也希望将它导出到csv,但完全搞清楚是第一部分。谢谢:))

# Bring in the module Twython which pulls from Twitter's API
from twython import Twython, TwythonError

# Making variables for my twitter API keys 
CONSUMER_KEY = 'my personal input hered'
CONSUMER_SECRET = 'my personal input here'
ACCESS_KEY = 'my personal input here'
ACCESS_SECRET = 'my personal input here'

twitter = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)

## 1) This block works and searches for tweets containing a specific keyword
print(twitter.search(q='python'))

## 2) This block works as well and returns all tweets by username
try:
   user_timeline = twitter.get_user_timeline(screen_name='')
except TwythonError as e:
   print e
for tweets in user_timeline:
print tweets['text']

## 3) I can't get this one to work. It is supposed to return all tweets by
#     username AND containing keyword
*try:
   user_timeline = twitter.get_user_timeline(screen_name='ThePSF') and twitter.search(q='lines')
except TwythonError as e:
   print e
for tweets in user_timeline and q:
   print tweets['text']*

1 个答案:

答案 0 :(得分:0)

Twitter API不允许您在用户时间线内进行搜索 - 您必须自己在#2中进行搜索。

您在#3中所做的另一种选择是使用Search API(在本例中为twitter.search)并传递一个涵盖这两种情况的查询。一个例子是

twitter.search(q='from:ThePSF AND lines')

但请注意,搜索API仅限于7天的数据。