我一直在学习将 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])
我仍然得到与错误消息相同的结果?