从 Twitter 流式传输推文(使用 Tweepy 和 Python)并存储在 SQLite 数据库中,直到处理完 N 条推文
Stream tweets from Twitter (With Tweepy and Python) and store in SQLite database until N tweets has been processed
我试图在 SQLite 数据库 table ("sentiment") 中存储 N 条推文(通过关键字 "Trump" 过滤)。为此,我写了一个函数"count_rows",returns这个table中存储的整数行(每行对应一条tweet)。使用这个整数作为精确到达 N 条推文的截止点,我试图在 while 循环中流式传输推文(见下文):
N = 100
def count_rows():
count_SQL = """SELECT COUNT(*) FROM sentiment"""
c.execute(count_SQL)
return c.fetchall()[0][0]
num_rows = count_rows() # Starts at value: zero
while num_rows <= N:
try:
auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream(auth, listener())
twitterStream.filter(track=["Trump"])
# num_rows = count_rows()
except Exception as e:
print(str(e))
time.sleep(5)
num_rows = count_rows()
挑战在于,流式传输永远持续进行,而 while 循环是无限的。我究竟做错了什么?我是否以错误的方式使用 count_rows() ? (函数 count_rows() 本身可以正常工作,所以我想错误一定是在我的 while 循环逻辑中)。
[自我提示:记得阅读全部 post中的单词:]
编辑:
Streams [do] not terminate unless the connection is closed,
计数测试不应该在 侦听器内部吗?听起来对 Stream
的调用不会 return 到 while 函数。
这个num_rows = count_rows()
是否不断将num_rows重置为0? posted 代码中没有指示 sentiments
中的 COUNT(*)
发生变化。是否将推文插入 sentiment
table?
我试图在 SQLite 数据库 table ("sentiment") 中存储 N 条推文(通过关键字 "Trump" 过滤)。为此,我写了一个函数"count_rows",returns这个table中存储的整数行(每行对应一条tweet)。使用这个整数作为精确到达 N 条推文的截止点,我试图在 while 循环中流式传输推文(见下文):
N = 100
def count_rows():
count_SQL = """SELECT COUNT(*) FROM sentiment"""
c.execute(count_SQL)
return c.fetchall()[0][0]
num_rows = count_rows() # Starts at value: zero
while num_rows <= N:
try:
auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream(auth, listener())
twitterStream.filter(track=["Trump"])
# num_rows = count_rows()
except Exception as e:
print(str(e))
time.sleep(5)
num_rows = count_rows()
挑战在于,流式传输永远持续进行,而 while 循环是无限的。我究竟做错了什么?我是否以错误的方式使用 count_rows() ? (函数 count_rows() 本身可以正常工作,所以我想错误一定是在我的 while 循环逻辑中)。
[自我提示:记得阅读全部 post中的单词:]
编辑:
Streams [do] not terminate unless the connection is closed,
计数测试不应该在 侦听器内部吗?听起来对 Stream
的调用不会 return 到 while 函数。
这个num_rows = count_rows()
是否不断将num_rows重置为0? posted 代码中没有指示 sentiments
中的 COUNT(*)
发生变化。是否将推文插入 sentiment
table?