NameError:未定义类的名称

2024-06-16 12:51:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个类(searcher),用于在数据库中搜索字符串,但当我想执行脚本时,出现以下错误:

NameError: name 'searcher' is not defined

我的代码:

class searcher:
    def __init__(self, dbname):
        self.con = sqlite3.connect(dbname)

    def __del__(self):
        self.con.close()

    def getmatchrows(self,q):
        fieldlist = 'w0.urlid'
        tablelist = ''
        clauselist = ''
        words = q.split(' ')
        tablenumber = 0
        wordids = []

        for word in words:
            wordrow = self.con.execute("select rowid from wordlist where word = '%s'" %word).fetchone()
            if wordrow !=None:
                wordid = wordrow[0]
                wordids.append(wordid)
                if tablenumber > 0:
                    tablelist+=','
                    clauselist+=' and '
                    clauselist+='w%d.urlid=w%d.urlid and ' % (tablenumber -1, tablenumber)
                fieldlist+=',w%d.location'% tablenumber
                tablelist+='wordlocation w%d'% tablenumber
                clauselist+='w%d.wordid = %d' % (tablenumber,wordid)
                tablenumber+=1

        query = 'select %s from %s where %s' % (fieldlist,tablelist,clauselist)
        cur = self.con.execute(query)
        rows = [row for row in cur]

        return rows,wordids

    wordsearch = searcher('searchindex.db')
    print  wordsearch.getmatchrows('indie music')

我做错什么了?!!你知道吗


Tags: selfdefconwordtablelistdbnamesearcherfieldlist
1条回答
网友
1楼 · 发布于 2024-06-16 12:51:31

代码的最后两行是缩进的,因此它们属于class searcher:块。但是,searcher类在该块结束之前不存在,因此尝试引用wordsearch = searcher('searchindex.db')中的searcher失败。你知道吗

取消插入最后两行。你知道吗

相关问题 更多 >