为了避免推文被推特垃圾邮件过滤器捕获,我有一些代码转到tinyurl,并在每次为每个原始URL运行代码时创建一个新的短URL。我想要的是每次打印'u'
时,它的值都应该传递给变量'linkvar1', 'linkvar2', 'linkvar3'
等等。这是稍后在代码中传递给推文提交的:
import simplejson
import httplib2
import twitter
import tinyurl
print("Python will now attempt to submit tweets to twitter...")
try:
api = twitter.Api(consumer_key='',
consumer_secret='',
access_token_key='',
access_token_secret='')
for u in tinyurl.create('http://audiotechracy.blogspot.co.uk/2014/03/reviewing-synapse-antidote-rack.html',
'http://audiotechracy.blogspot.co.uk/2014/03/free-guitar-patches-for-propellerhead.html',
'http://audiotechracy.blogspot.co.uk/2014/02/get-free-propellerhead-rock-and-metal.html',
):
print u
linkvar1 = u
linkvar2 = u
linkvar3 = u
status = api.PostUpdate("The new Synapse Antidote Rack Extension:" + linkvar1 + " #propellerhead #synapse")
status = api.PostUpdate("Free Propellerhead guitar patches for everyone!" + linkvar2 + " #propellerhead #reason #guitar")
status = api.PostUpdate("Free Metal and Rock drum samples!" + linkvar3 + " #propellerhead #reason)
print("Tweets submitted successfully!")
例外,e: 打印 str(e)
print("Twitter 提交失败!!")
然而,目前所做的只是使用最后为所有提交的推文生成的 tinyurl。我敢肯定这是一个简单的解决方案,我只是很愚蠢,但有谁知道如何做我想做的事?
谢谢
您的问题是您没有通过每个循环对linkvar
变量执行任何操作。因此,每次循环运行时,它们都会被覆盖。
您有几个选择
选项 1:将linkvar
设置为附加到每个循环的列表
linkvar1 = []
for u in ...
...
linkvar1.append(u)
# Post to twitter
for p in linkvar1:
status = api.PostUpdate("The new Synapse Antidote Rack Extension:" + p + " #propellerhead #synapse")
status = api.PostUpdate("Free Propellerhead guitar patches for everyone!" + p + " #propellerhead #reason #guitar")
status = api.PostUpdate("Free Metal and Rock drum samples!" + p + " #propellerhead #reason)
在第一个 for 循环结束时,您将在 linkvar
变量中获得值。我不确定你为什么要使用三个,我是否将其切成单个实例。然后,您可以使用另一个for
循环进行循环,或者将批发传递给您自己的函数,该函数将适当地处理它们。无论哪种情况,您的所有网址现在都位于每个变量的列表中
选项 2:调用要在每个循环上执行的函数
for u in ...
...
MyTwitterFunction(u)
def MyTwitterFunction(url):
status = api.PostUpdate("The new Synapse Antidote Rack Extension:" + url + " #propellerhead #synapse")
status = api.PostUpdate("Free Propellerhead guitar patches for everyone!" + url + " #propellerhead #reason #guitar")
status = api.PostUpdate("Free Metal and Rock drum samples!" + url + " #propellerhead #reason)
每次迭代循环时,都会调用值为 u
的 MyTwitterFunction
。
选项 3:将发布代码直接拉入for
循环
for u in ...
status = api.PostUpdate("The new Synapse Antidote Rack Extension:" + u + " #propellerhead #synapse")
status = api.PostUpdate("Free Propellerhead guitar patches for everyone!" + u + " #propellerhead #reason #guitar")
status = api.PostUpdate("Free Metal and Rock drum samples!" + u + " #propellerhead #reason)
这消除了对linkvar
变量和额外for
循环的需求。您可以直接从创建 URL 的循环中发布。
我不确定"传递给变量"是什么意思。看起来好像您将 u 的值分配给 3 个变量中的每一个,然后覆盖它 - 例如:
for x in range(5):
y = x
将导致将值 4 分配给 y。你也许想列一个清单吗?例如:
y = []
for x in range(5):
y.append(x)
这将导致
y = [0,1,2,3,4]
我认为这就是您对链接1,2,3变量的目标。