4

我一直在学习将 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])

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

4

2 回答 2

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))
于 2012-08-13T21:46:47.570 回答
3

execute只接受两个参数;第二个是您要在准备好的 SQL 语句中使用的所有值的元组。所以,而不是

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

将所有值包装在一个元组中:

spot.execute("INSERT INTO Words VALUES(?,?)", (word_count, word) )
#                                             ^                ^
于 2012-08-13T21:47:25.263 回答