我不知道如何用图像发布其他推文。
我有一个要发布的推文(3)和要发布的3张图片的txt:
但是我的代码对所有图像都发布了相同的推文。
my_file = open('tweets.txt','r')
file_lines = my_file.readlines()
my_file.close
filenames = ['IMG/img1.jpg','IMG/img2.jpg','IMG/img3.png']
for line in file_lines:
for filename in filenames:
imagePath = filename
api.update_with_media(imagePath,line)
filenames = filenames[1:]
nap = randint(1,60)
time.sleep(nap)
答案 0 :(得分:0)
我已经简化了您的代码,以使您了解发生了什么事情:
tweets = ["tweet 1", "tweet 2", "tweet 3"]
images = ["image 1", "image 2", "image 3"]
for t in tweets:
for i in images:
print(t + " with " + i)
images = images[1:]
输出:
tweet 1 with image 1
tweet 1 with image 2
tweet 1 with image 3
发生了什么事?
您有两个for
循环,一个在另一个循环中,说:
对于每条推文,对于每张图片,请向我显示推文+图片,然后删除 列表中的第一张图片
所以您的程序要做的是:
# first iteration of 'tweets' list
tweet = "tweet 1"
# first iteration of 'images' list
image = "image 1"
print tweet + image # ("tweet 1" and "image 1")
# remove first image from 'images' ("images 1")
# second iteration of 'images' list (notice that tweet is still "tweet 1")
image = "image 2"
print tweet + image # ("tweet 1" and "image 2")
# remove first image from 'images' ("images 2")
# third iteration of 'images' list (notice that tweet is still "tweet 1")
image = "image 3"
print tweet + image # ("tweet 1" and "image 2")
# remove first image from 'images' ("images 3")
# second iteration of 'tweets' list
tweet = "tweet 2"
# 'images' list is now empty, so nothing will be iterated (nor printed)
# third iteration of 'tweets' list
tweet = "tweet 3"
# 'images' list is now empty, so nothing will be iterated (nor printed)
那该怎么办?
假设列表的长度相同,n
,则可以按从0
到n-1
的索引来选择项目:
tweets = ["tweet 1", "tweet 2", "tweet 3"]
images = ["image 1", "image 2", "image 3"]
for n in range(len(images)):
print(tweets[n] + " with " + images[n])
输出:
tweet 1 with image 1
tweet 2 with image 2
tweet 3 with image 3
如果您想更进一步,Python内置了一个将 zip 压缩在一起的内置列表,其中包括2个列表:函数zip()
tweets = ["tweet 1", "tweet 2", "tweet 3"]
images = ["image 1", "image 2", "image 3"]
my_tweets = zip(tweets, images)
for tweet, image in my_tweets:
print(tweet + " with " + image)
还有许多其他解决方案,但是这2个应该对您来说很好。如果您在代码中不再需要这些推文,请使用第一个。如果要再次使用它们,请使用zip
。
由您执行最后一步以实际发布推文。祝你好运!