python - sqlite3 : create function regexp with python

标签 python sql python-3.x sqlite

python 3.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()

谢谢

最佳答案

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

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())

将打印

[('This is a test message',)]
[('This is a test message',), ('Another message',)]
[('This is a test message',), ('Another message',)]

关于python - sqlite3 : create function regexp with python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50063058/

相关文章:

Python:绘制筛选点返回图片上的点

SQL 服务器 2012 : Add a linked server to PostgreSQL

python - 从 Qrunnable 连接一个 pyqtSignal

使用 Pickle 快速创建 Python 字典?

python - python模块.exe文件的无人值守安装

Mysql:忽略表中的2个不同的列

mysql - 如何使用sql查询结果来使用date_add

python-3.x - 比较来自两个数据帧的列并删除 df2 中与 df1 中的值相差 +/-0.03 范围内的行

python - 当数组数据类型和格式说明符不匹配时,如何将数组堆栈保存到 .csv?

python - 在评估 TensorFlow 模型时,如何在单个前向调用中查看特定隐藏层的值?