在Python中从文本文件读取时避免重复的字符串

问题描述 投票:0回答:1

我创建了一个Twitter机器人,用于发布3000个列表中的描述性形容词。我遇到问题,因为Tweepy错误表示状态重复,它会崩溃。

我认为最好的解决方案是在打印后从文本文件中删除该行,实现此目的的最佳方法是什么?

这里是我到目前为止编写的代码的主要部分:

import random
import tweepy
import time
from auth import consumer_secret, consumer_key, access_token_secret, access_token

api = tweepy.API(auth)

starttime = time.time()
while True:
    file = open('words.txt', 'r')
    random_word = random.choice(file.readlines())
    tweet = ('The %s tree.' % random_word.strip())
    api.update_status(status=tweet)
    print('Tweeted: %s' % tweet)
    time.sleep(1800.0 - ((time.time() - starttime) % 1800.0))
python api twitter duplicates status
1个回答
0
投票

您当前正在循环的每次迭代中读取整个过程。更好的选择是阅读一次,将行打乱并对其进行处理:

from random import shuffle

with open('words.txt', 'r') as f:
    lines = [line.strip() for line in f.readlines()]

shuffle(lines)

for line in lines:
    tweet = 'The {} tree.'.format(line)
    api.update_status(status=tweet)
    print('Tweeted: ', tweet)
© www.soinside.com 2019 - 2024. All rights reserved.