【问题标题】:sqlite3 : create function regexp with pythonsqlite3:用python创建函数正则表达式
【发布时间】:2018-04-27 13:05:12
【问题描述】:

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

谢谢

【问题讨论】:

    标签: python sql python-3.x sqlite


    【解决方案1】:

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

    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',)]
    

    【讨论】:

      【解决方案2】:

      documentation 说:

      REGEXP 运算符是 regexp() 用户函数的特殊语法。 … "X REGEXP Y" 运算符将被实现为对 "regexp(Y,X)" 的调用。

      你的函数必须有两个参数。

      【讨论】:

      • 所以我必须写data = leCursor.execute('SELECT * FROM tweet WHERE texte pattern REGEXP ?',mot).fetchall()connexion.create_function("REGEXP", 2, fonctionRegex)
      • 函数是fonctionRegex
      猜你喜欢
      • 2020-03-17
      • 1970-01-01
      • 2013-01-02
      • 1970-01-01
      • 1970-01-01
      • 2012-01-02
      • 2010-10-01
      • 1970-01-01
      • 2023-03-28
      相关资源
      最近更新 更多