它似乎忽略了if self.i >5:
语句(我删除了我的键)。推文应该在几条推文之后停止流式传输,但不断流式传输直到程序停止。我已经尝试sys.exit()
并最终返回工作。
from bottle import route, default_app, get, post, request, run
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import smaclient
import MySQLdb
import sys
from textblob import TextBlob
ckey = ''
csecret = ''
atoken = ''
asecret = ''
license_key = '
@route('/')
def hello():
return '''
</br></br></br></br></br></br>
<h1 align="center">Gavin's Twitter Sentiment Analysis</h1>
<p align="center">Enter a word into the search box below</p>
<form action="/page2" method="post" align="center">
Search: <input name="search" type="text" />
<input value="Search" type="submit" />
</form>
'''
@route('/page2', method='POST')
def result():
search = request.forms.get('search')
result = analyze(search)
return result
def analyze(subject):
auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream(auth, listener())
return twitterStream.filter(track=[subject])
class listener(StreamListener):
i = 0
def on_data(self, data):
print data
tweet = data.split(',"text":"')[1].split('","source')[0]
print tweet
db = MySQLdb.connect(
host='localhost',
user='root',
passwd='',
db='sentiment'
)
cursor = db.cursor()
no = 2
cursor.execute('INSERT INTO tweets (Tweet, no) VALUES (%s, %s)', (tweet, no))
db.commit()
positive = 0
negative = 0
self.i += 1
if self.i > 5:
cursor = db.cursor()
cursor.execute("SELECT * FROM tweets")
rows = cursor.fetchall()
for eachRow in rows:
tweet = eachRow[0]
blob = TextBlob(tweet)
blob.language = 'en'
polarity = blob.sentiment.polarity
if (polarity < - 0.10):
negative += 1
elif (polarity > 0.10):
negative += 1
cursor.execute('DELETE FROM tweets WHERE no = 2')
db.commit()
if positive > negative:
return 'positive'
else:
return 'negative'
sys.exit()
run(host='localhost', port=7000, debug=True)