我得到了一个函数,该函数在用户每次输入内容时都会计算响应。该函数从数据库获取响应。我不明白的是,为什么每次每次调用函数时都要重新定义包含数据库中所有数据的变量(我将其称为intents_db)?我曾尝试将其放在函数之外,但随后我的程序仅在第一次运行时有效,但是在用户第二次输入内容时返回空答案。
def response(sentence, user_id='1'):
results = classify_intent(sentence)
intents_db = c.execute("SELECT row_num, responses, tag, responses, intent_type, response_type, context_set,\
context_filter FROM intents")
if results:
# loop as long as there are matches to process
while results:
if results[0][1] > answer_threshold:
for i in intents_db:
# print('tag:', i[2])
if i[2] == results[0][0]:
print(i[6])
if i[6] != 'N/A':
if show_details:
print('context: ', i[6])
context[user_id] = i[6]
responses = i[1].split('&/&')
print(random.choice(responses))
if i[7] == 'N/A' in i or \
(user_id in context and i[7] in i and i[7] == context[
user_id]):
# a random response from the intent
responses = i[1].split('&/&')
print(random.choice(responses))
print(i[4], i[5])
print(results[0][1])
elif results[0][1] <= answer_threshold:
print(results[0][1])
for i in intents_db:
if i[2] == 'unknown':
# a random response from the intent
responses = i[1].split('&/&')
print(random.choice(responses))
initial_comm_output = random.choice(responses)
return initial_comm_output
else:
initial_comm_output = "Something unexpected happened when calculating response. Please restart me"
return initial_comm_output
results.pop(0)
return results
此外,我开始进入数据库和sqlite3,因为我想长期建立一个庞大的数据库。因此,我必须完全加载整个数据库似乎也很低效。有什么方法可以只加载所需的数据行吗?我的数据库中有一个row_number列,所以如果可以这样说: “在意图中选择WHERE row_num = 2” 那样很好,但是我不知道该怎么做。
答案 0 :(得分:1)
cursor.execute()
返回一个迭代器,您只能在其上循环一次。
如果要重复使用,请将其转换为列表:
intents_db = list(c.execute("..."))
答案 1 :(得分:0)
因此,我必须完全加载整个数据库似乎也没有效率。有什么方法可以只加载所需的数据行吗?我的数据库中有一个row_number列,因此,如果可以这样说:“ SELECT WHERE row_num = 2 FROM intents”会很棒,但我不知道该怎么做。
您几乎明白了:是
intents_db = c.execute("SELECT row_num, responses, tag, responses, intent_type,
response_type, context_set, context_filter
FROM intents WHERE row_num=2")
但是不要犯其他数据库初学者犯的错误,并尝试将程序中的某些变量直接放入该字符串中。这使得程序易于进行SQL注入。
相反,做
row_num = 2
intents_db = c.execute("SELECT row_num, responses, tag, responses, intent_type,
response_type, context_set, context_filter
FROM intents WHERE row_num=?", (row_num,))
当然,您还可以设置其他字段的条件。