gpt4 book ai didi

mysql - 插入mysql数据库而不是打印

转载 作者:行者123 更新时间:2023-11-30 01:13:51 25 4
gpt4 key购买 nike

我对使用 Python 还很陌生,我希望将 Twitter 数据收集到我的 MySQL 数据库中以用于项目。我有用于从本教程收集数据的脚本:

import re
from re import sub
import time
import cookielib
from cookielib import CookieJar
import urllib2
from urllib2 import urlopen
import difflib

cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders = [('User-agent', 'Mozilla/5.0')]

keyWord = 'nyc'
startingLink = 'https://twitter.com/search/realtime?q='

# begin loop

def main():

oldTwit = []
newTwit = []
while 1 < 2:
try:
sourceCode = opener.open ('https://twitter.com/search/realtime?q='+keyWord+'&src=hash').read()
splitSource = re.findall (r' <p class="js-tweet-text tweet-text">(.*?)</p>',sourceCode)
for item in splitSource:
#print item
print ''
print ''
print ' '
aTweet = re.sub(r'<.*?>', '',item)
print aTweet
newTwit.append(aTweet)

comparison = difflib.SequenceMatcher(None, newTwit, oldTwit)
howSim = comparison.ratio()
print '##############'
print howSim

oldTwit = [None]
for eachItem in newTwit:
oldTwit.append(eachItem)

newTwit = [None]

time.sleep(howSim*10)

except Exception, e:
print str(e)
print 'errored in the main try'
time.sleep(555)

main()

这为我提供了我想要收集的推文(我并不是真的想分析这些数据,我更多的是尝试使用 python 连接到我的数据库自动收集数据。)

我还使用 MySQLdb 连接了数据库,并且能够使用简单的插入语句将内容添加到我的数据库:

import MySQLdb
db=MySQLdb.connect(host="127.0.0.1",user="root",passwd="",db="twitinfo")
cursor = db.cursor()
sql = "INSERT INTO tweets(text) VALUES ('?')"
cursor.execute(sql)
db.commit()

所以我的问题是如何用插入语句“替换” print ,以及我需要添加什么才能使我的值成为推文文本?我进行了高低搜索,但没有发现任何对此有帮助的信息。我自己也尝试过,但作为一个Python新手,试图猜测其语法就像大海捞针一样。

最佳答案

您显示的 SQL 是将一个由单个问号组成的字符串插入到数据库中。您需要使用 VALUES(?) 指定值的占位符,并且需要将值传递给执行函数以供其插入,可能如下所示:

sql = "INSERT INTO tweets(text) VALUES (?)"
value = "Apoplectic Fits"
cursor.execute(sql, value)

您需要将导入行添加到顶部的Python,并连接到循环外部的数据库。您可以将光标创建行放在循环之外。在循环内,您使用推文消息代替 value

<小时/>

阅读 MySQLdb 的文档后(使用新模块时的推荐做法),您需要使用 %s 作为占位符,而不是 ?

如果您想将数据插入到变量aTweet中,则:

sql = "INSERT INTO tweets(text) VALUES (%s)"
cursor.execute(sql, aTweet)

未经测试。从理论上讲,理论和实践没有区别;实际上,是有的。

关于mysql - 插入mysql数据库而不是打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19250656/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com