通过Twitter API提取热门标签
我正在使用以下代码来运行一个推特机器人,这个机器人应该在发推时使用当前热门的标签,并且它会用这些标签来发布一些著名哲学家的想法。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import tweepy, time, sys
argfile = str(sys.argv[1])
#enter the corresponding information from your Twitter application:
CONSUMER_KEY = 'secret'
CONSUMER_SECRET = 'secret'
ACCESS_KEY = 'secret'
ACCESS_SECRET = 'secret'
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
filename=open(argfile,'r')
f=filename.readlines()
filename.close()
trends1 = api.trends_place(1)
print trends1
hashtags = [x['name'] for x in trends1[0]['trends'] if x['name'].startswith('#')]
# print hashtags
print hashtags[0]
trend_hashtag = hashtags[0]
# Tweet every X min ...
for line in f:
api.update_status(line + ' ' + trend_hashtag)
time.sleep(1800)
问题是,代码在第一次运行时就把热门标签永久存储下来了。我该怎么做才能让每次发推时都重新提取标签呢?(在这个例子中,每1800秒提取一次)
提前谢谢你!
1 个回答
3
显而易见的变化是要在你的循环里面更新标签。
for line in f:
trends1 = api.trends_place(1)
print trends1
hashtags = [x['name'] for x in trends1[0]['trends'] if x['name'].startswith('#')]
# print hashtags
print hashtags[0]
trend_hashtag = hashtags[0]
api.update_status("{0} {1}".format(line, trend_hashtag)) # more modern format
time.sleep(1800)