python - 让我的 Tweepy 流停止时遇到问题
问题描述
一旦达到 100 条推文,就无法让我的流退出。我尝试了很多方法。希望保持“开放”的用法。
*在文件打开时使用 while 循环会导致杂乱无章的 JSON 文件 *当前使用的断开连接在达到 100 后会继续流式传输,但数据已损坏
编辑:
- 使用 self 重新创建了推文数量和推文总数。
- 每次加载数据时,都会更新 num_tweets:self.num_tweets+=1。然后更新pbar:self.pbar.update(1)
- 在 try 语句之外,如果 self.num_tweets < self.total_tweets,则返回 True,否则 self.pbar.close() 并返回 False
信用:克里斯库克曼
def __init__(self, api=None):
self.num_tweets = 0
self.total_tweets = int(input("Number of tweets:"))
self.pbar = tqdm(total=self.total_tweets)
self.unsaved = 0
self.emojis = 0
def on_data(self, data):
try:
portal_1 = creds()
rawTweets = json.loads(data)
self.num_tweets += 1
self.pbar.update(1)
...
...
except BaseException as e:
print(colored("Error on_data: %s", "red") % str(e))
if self.num_tweets < self.total_tweets:
return True
else:
self.pbar.close()
return False
解决方案
要使用 tweepy 退出流,您需要从 on_status 函数返回 false,因此如果您更改:
if self.num_tweets < 100:
return True
else:
twitter_stream.disconnect()
至:
if self.num_tweets < 100:
return True
else:
self.pbar.close() # Closes the instance of the progress bar.
return False # Closes the stream.
那应该解决它。顺便说一句,每次运行时添加 self.num_tweets 以获取进度条:
self.pbar.update(self.num_tweets)
通过更新,您每次都添加推文数量:
推文 1 | 推文数 = 的 1 | 进度条 = 的 1 (1)
推文 2 | 推文数 = 的 2 | 进度条 = 的 1 + 2 (3)
推文 3 | 推文数 = 的 3 | 进度条 = 的 3 + 3 (6)
从您的代码中,我假设您的意图是增加它们,所以要做到这一点,您只需将其更改为:
self.pbar.update(1)
希望这可以帮助。
推荐阅读
- java - 根据使用 Thymeleaf 选择的选择选项更改 HTML 表单布局
- python - 带参数的生成器?
- flutter - 找不到框架flutter_plugin_android_lifecycle颤振
- python - 正则表达式在数字范围内查找匹配项
- c# - 有没有办法让一个类知道订阅它的委托的东西成功运行了?
- jquery - 我想在 jQuery Datepicker 中禁用特定的假期和星期几
- typescript - 如何使用 Angular 10 实现拖放流程图?
- angular - 无法读取未定义的属性“storageKey”
- python - 你如何在python中将整数写入外部文件
- java - 使用 Docker 构建一个 Maven 项目并作为 Flink 作业提交