Tweepy 不将重复的推文存储到数据库中

Tweepy to not store duplicate tweets into database

我正在使用 Tweepy 获取推文并将所有推文存储到数据库中。但我现在面临的问题是 Tweepy 还会将重复的推文存储到数据库中。

下面是我使用的代码:

from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
from flask_sqlalchemy import SQLAlchemy
from models import TrainingTweets, db
import mysql.connector
import json
import tweepy
from tweepy.api import API

#consumer key, consumer secret, access token, access secret.
ckey=""
csecret=""
atoken="-"
asecret=""

auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)

api = tweepy.API(auth)


class listener(StreamListener):

    def __init__(self, api=None):
        self.api = api or API()
        self.n = 0
        self.m = 50

    def on_data(self, data):
        all_data = json.loads(data)
        self.n = self.n+1
        if self.n <= self.m:
            tweet = all_data["text"]
            username = all_data["user"]["screen_name"]
            label = "1"
            ttweets = TrainingTweets(label_id=label, tweet_username=username, tweet=tweet)
            db.session.add(ttweets)
            db.session.commit()
            print((username, tweet))
            return True
        else:
            print("Successfully stored ", self.m, " tweets into database")
            return False

    def on_error(self, status):
        print(status)

auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)

twitterStream = Stream(auth, listener())
twitterStream.filter(track=["health"], languages=["en"], follow="")

谁能帮我让 Tweepy 只存储一条推文而不是所有重复的推文到数据库中?

由于该程序会自动将来自 Twitter 用户的传入推文直接存储到您的数据库中,因此您有几个选择。你可以:

  1. 首先将所有推文存储到一个集合中(这是一个 'unordered collection of unique values'),然后将该集合的元素保存到您的数据库中 -(也许以某个预定的时间间隔?)。以下是有关集合的一些信息:http://www.openbookproject.net/books/bpp4awd/ch06.html

  2. 不理会程序的逻辑,但最后清除数据库中的重复项。以下是有关删除数据库中重复记录的一些信息:http://www.sqlteam.com/article/deleting-duplicate-records