2017-04-25 18 views
-1

我有一個聊天bot django Web應用程序,它接受用戶輸入並嘗試在數據庫中查找匹配的輸入,然後檢索相應的輸出。使用字符串變量與REGEXP在python3中選擇pymysql查詢

這是chatbot.py代碼的一部分:

# -*- coding: utf-8 -*- 
import re,string,sys 
import codecs 
import types 
import nltk 
import csv 
import pymysql 
from nltk import pos_tag 
from nltk.tokenize import regexp_tokenize 
from nltk.tokenize import word_tokenize 
from nltk.stem.isri import ISRIStemmer 
from chatbotx1.arabic_const import * 
from chatbotx1.normalize import * 
from chatbotx1.stemming import * 
from nltk.tag.stanford import StanfordPOSTagger 
from chatbotx1.ar_ghalat import * 
from chat.models import chat, user_info 

# initialize the connection to the female_database 
conn = pymysql.connect("***","***","***","***") 
cursor = conn.cursor() 
conn.text_factory = str 

def run_conversation_male(): 
     last_B =' '.join(chat.objects.values_list('chatbot_response', flat=True).latest('id')) 
     H = ' '.join(chat.objects.values_list('user_iput', flat=True).latest('id')) 
     New_H= ' '.join(PreProcess_text(H)) 
     cursor.execute('SELECT respoce FROM Male_Conversation_Engine WHERE request REGEXP?',[New_H]) 
     reply = cursor.fetchone() 
     if reply: 
      B8=reply[0] 
      new_data(H,B8) 
      ID = chat.objects.values_list('id', flat=True).latest('id') 
      chat.objects.filter(id=ID).update(chatbot_response=B8) 

我使用sqlite3的,但現在使用MySQL後,我得到這個錯誤信息:

TypeError: not all arguments converted during string formatting 

我曾嘗試這個解決方案:

openconnect = pymysql.connect(host='xxxx',port=3306,user='xxx',passwd='xxx',db='xxxx',charset='utf8') 

我得到這個錯誤信息:

pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax;) 

(PS:我是用Python3.5,MySQL和pymysql,Django10,文本是阿拉伯語)

+0

刪除'''從'REGEXP和檢查的'REGEXP' MySQL的語法?。 –

+0

@EminMastizada謝謝你,我試過刪除?但它仍然是相同的字符串形成error.Also,我試圖找到REGEXP的MySQL語法,但我沒有找到和資源 – Eman

+0

REGEXP的Mysql文檔:https://dev.mysql.com/doc/refman/5.7/ en/regexp.html –

回答

0

問題的語法是,cursor.execute不知道在哪裏把New_H。您需要%s來標記該變量的位置。 嘗試改變你的SQL這一個:

SELECT respoce FROM Male_Conversation_Engine WHERE request REGEXP %s 
+0

我再次得到這個錯誤:'UnicodeEncodeError:'拉丁-1'編解碼器不能編碼字符'\\ u0631'的位置68:序號不在範圍內(256)' – Eman

+0

結帳:https://dasprids.de/blog/2007/12/17/python-mysqldb-and-utf-8/ –

相關問題