如何从字符串中提取值并在数据库查询中使用这些值?

时间:2019-04-16 04:29:54

标签: python chatbot stemming ner

我正在尝试从句子/问题中提取自定义实体,并针对数据库进行查询,问题是我在提取实体时遇到了麻烦。

我的表有10,000行,看起来像这样:

Car type | Owner
------------------
Sedan    | John
Hatchback| Mary

我希望程序回答一个示例问题:

  

“谁购买了轿车?”

理想情况下,正确的答案是John

我能否使程序理解下面句子的上下文并正确回答?

这意味着引擎应该:

  1. 理解句子“谁购买了轿车”中的“轿车”是实体(汽车类型),并将其翻译为Car Type = Sedan

  2. 理解句子中的“购买”一词与“所有者”的含义相同。

我们假设所有者与购买者相同,没有租赁或任何类似的东西。

最终目标是了解这句话中的实体并将其转换为SQL查询。

1 个答案:

答案 0 :(得分:0)

您正在寻找的东西叫做NLTK,代表自然语言(处理)工具包。

要让您大致了解该库的功能,以下是NLTK主页上的演示代码,向您展示了如何标记和标记文本:

import nltk
sentence = "At eight o'clock on Thursday morning Arthur didn't feel very good."
tokens = nltk.word_tokenize(sentence)
print(tokens)
tagged = nltk.pos_tag(tokens)
print(tagged[0:6])

预期输出:

['At', 'eight', "o'clock", 'on', 'Thursday', 'morning', 'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']
[('At', 'IN'), ('eight', 'CD'), ("o'clock", 'JJ'), ('on', 'IN'), ('Thursday', 'NNP'), ('morning', 'NN')]

现在,考虑到您的要求多么简单,您甚至可能不需要像NLTK这样复杂的库来解决问题,您可以使用简单的预定字符串搜索程序。

例如,如果您只需要回答以下几个问题:

  

“谁拥有[x]型汽车?”

     

“有多少人拥有[x]型汽车?”

     

“ [x]拥有哪种类型的汽车?”

您可以使用Regex查找与预定问题匹配的内容:

import re

# get the question
question = "What kind of car does Joe own?"

# use regex to find matches for predefined question formats
car_type_for_match = re.findall(r"What type of car does (.*?) own\?", question)

if car_type_for_match and len(car_type_for_match) > 0:
  print("Car type for: {}".format(car_type_for_match))

稍后您可以使用更多if语句进行扩展以添加更多问题。

祝你好运。

相关问题