sqlite3:用python创建函数regexp

2024-10-02 22:28:24 发布

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

Python3.6。我试图为sqlite3创建一个REGEXP函数。我有个错误:OperationalError: wrong number of arguments to function REGEXP()

这是我的代码:

import sqlite3
import re

def fonctionRegex(mot):
    patternRecherche = re.compile(r"\b"+mot.lower()+"\\b")
    return patternRecherche.search(item) is not None

dbName = 'bdd.db'
connexion = sqlite3.connect(dbName)
leCursor = connexion.cursor()
connexion.create_function("REGEXP", 1, fonctionRegex)

mot = 'trump'
data = leCursor.execute('SELECT * FROM tweet WHERE texte REGEXP ?',mot).fetchall()

谢谢


Tags: 函数importre错误functionsqlite3dbnameregexp
2条回答

你做错了什么。这是更正确的例子

import sqlite3
import re


def functionRegex(value, pattern):
    c_pattern = re.compile(r"\b" + pattern.lower() + r"\b")
    return c_pattern.search(value) is not None


connection = sqlite3.connect(':memory:')
cur = connection.cursor()
cur.execute('CREATE TABLE tweet(msg TEXT)')
cur.execute('INSERT INTO tweet VALUES("This is a test message")')
cur.execute('INSERT INTO tweet VALUES("Another message")')

connection.create_function("REGEXP", 2, functionRegex)

print(cur.execute('SELECT * FROM tweet WHERE REGEXP(msg, ?)', ('test',)).fetchall())
print(cur.execute('SELECT * FROM tweet WHERE REGEXP(msg, ?)', ('message',)).fetchall())
print(cur.execute('SELECT * FROM tweet WHERE ? REGEXP msg', ('message',)).fetchall())

将打印

^{pr2}$

documentation上写着:

The REGEXP operator is a special syntax for the regexp() user function. … the "X REGEXP Y" operator will be implemented as a call to "regexp(Y,X)".

函数必须有两个参数。在

相关问题 更多 >