gpt4 book ai didi

插入 sqlite3 值时出现 Python TypeError?

转载 作者:IT王子 更新时间:2023-10-29 06:30:58 25 4
gpt4 key购买 nike

我一直在学习将 sqlite3 与 python 结合使用。现在,我有一个函数可以接受一个词并在互联网上查找该词的定义。然后,我尝试将单词存储在一个表中,将定义存储到另一个通过外键链接在一起的表中。

像这样:

#! /usr/bin/env python
import mechanize
from BeautifulSoup import BeautifulSoup
import sys
import sqlite3

def dictionary(word):
br = mechanize.Browser()
response = br.open('http://www.dictionary.reference.com')
br.select_form(nr=0)
br.form['q'] = word
br.submit()
definition = BeautifulSoup(br.response().read())
trans = definition.findAll('td',{'class':'td3n2'})
fin = [i.text for i in trans]
query = {}
word_count = 1
def_count = 1
for i in fin:
query[fin.index(i)] = i
con = sqlite3.connect('vocab.db')
with con:
spot = con.cursor()
spot.execute("SELECT * FROM Words")
rows = spot.fetchall()
for row in rows:
word_count += 1
spot.execute("INSERT INTO Words VALUES(?,?)", word_count,word)
spot.execute("SELECT * FROM Definitions")
rows = spot.fetchall()
for row in rows:
def_count += 1
for q in query:
spot.execute("INSERT INTO Definitions VALUES(?,?,?)", def_count,q,word_count)
return query

print dictionary(sys.argv[1])

当我运行它时:

./database_trial.py 'pass'

这是错误信息:

Traceback (most recent call last):
File "./database_trial.py", line 37, in <module>
print dictionary(sys.argv[1])
File "./database_trial.py", line 28, in dictionary
spot.execute("INSERT INTO Words VALUES(?,?)", word_count,word)
TypeError: function takes at most 2 arguments (3 given)

在函数内部,我只有两个参数传递给“Words”表,但是消息说有三个?

spot.execute("INSERT INTO Words VALUES(?,?)", word_count,word) 

我想我可能把 sys.argv 弄乱了。所以我仔细检查并将该行更改为:

spot.execute("INSERT INTO Words VALUES(?,?)", word_count, sys.argv[1])

我仍然得到与错误消息相同的结果?

最佳答案

spot.execute("INSERT INTO Words VALUES(?,?)", word_count,word) 

三个参数被传递给方法 spot.execute:SQL 字符串、变量 word_count 和变量 。我怀疑要输入数据库的值需要包含在元组中以形成单个参数:

spot.execute("INSERT INTO Words VALUES(?,?)", (word_count,word))

关于插入 sqlite3 值时出现 Python TypeError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11942735/

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