我使用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="")
&#13;
任何人都可以帮助我让Tweepy只存储一条推文,而不是将所有重复的推文存入数据库吗?
答案 0 :(得分:0)
由于程序会自动将来自Twitter用户的传入推文存储到您的数据库中,因此您有几个选择。你可以:
首先将所有推文存储到一个集合中(这是唯一值的'无序集合),然后将集合的元素保存到数据库中 - (可能在某些预定间隔?)。以下是有关集合的一些信息:http://www.openbookproject.net/books/bpp4awd/ch06.html
单独保留程序的逻辑,但最后清除重复数据库。以下是有关删除数据库中重复记录的一些信息:http://www.sqlteam.com/article/deleting-duplicate-records