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

2024-03-28 16:30:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从一个句子/问题中提取自定义实体,并在数据库中查询它们,问题是在提取实体时遇到了问题。你知道吗

我的表有10000行,如下所示:

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

我想让程序回答一个示例问题:

"Who purchased the sedan?"

理想情况下,这里的正确答案是John。你知道吗

我是否有可能让程序理解以下句子背后的上下文并正确回答?你知道吗

这意味着发动机应该:

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

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

让我们假设所有者和购买它的人是一样的,没有租赁或类似的东西。你知道吗

最终的目标是理解这句话中的实体并将其转换为SQL查询。你知道吗


Tags: 程序实体数据库示例typejohncar句子
1条回答
网友
1楼 · 发布于 2024-03-28 16:30:08

你要找的是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那样复杂的库来解决您的问题,您可以使用一个简单的预先确定的字符串搜索insead。你知道吗

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

"Who owns [x] type of car?"

"How many people own [x] type of car?"

"What type of car does [x] own?"

您可以使用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语句来扩展它以添加更多的问题。你知道吗

祝你好运。你知道吗

相关问题 更多 >