我一直在学习使用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])
我的错误信息仍然有相同的结果吗?
答案 0 :(得分:8)
spot.execute("INSERT INTO Words VALUES(?,?)", word_count,word)
将 三个参数传递给方法spot.execute
:SQL字符串,变量word_count
和变量word
。我怀疑要输入数据库的值需要包含在一个元组中以形成一个参数:
spot.execute("INSERT INTO Words VALUES(?,?)", (word_count,word))
答案 1 :(得分:3)