【发布时间】:2020-01-24 20:50:20
【问题描述】:
每次用户输入内容时,我都会调用一个函数来计算响应。该函数从数据库中获取响应。我不明白的是,为什么每次调用函数时我都必须重新定义包含数据库中所有数据的变量(我称之为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 列,所以如果有可能这样说: “从意图中选择行数 = 2” 那太好了,但我不知道该怎么做。
【问题讨论】:
-
SELECT whatever FROM intents WHERE row_num = 2 -
啊,好吧。谢谢!当我想在我的列标签中选择一行时,您会认为您可以这样做:“SELECT whatever FROM Intents WHERE tag = {}”.format(results[0][0])) (result[0][ 0] 是我想要获取对应行的标签)但是我收到错误:“没有这样的列” WHERE 只适用于整数吗?
-
您应该将用户提供的值绑定到查询中的参数,而不是尝试直接在查询字符串中插入随机内容。请参阅文档和此处的许多示例。
-
我明白了。非常感谢您的帮助!