我正在使用以下代码来运行一个Twitter机器人,该机器人应该在发布时使用一个位于趋势顶部的主题标签,并且机器人使用它来发布着名哲学家的想法。
#!/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秒)重新提取主题标签?
提前致谢!
答案 0 :(得分:3)
显而易见的变化是更新你的循环中的#em>标签:
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)