我正在用 python 构建一个聊天机器人。我需要从用户的输入文本中提取日期。一些测试用例如下:
1."last week of july"
2." in june"
3. "last month"
4. "last n days"
这些只是一个示例。提取日期后,我需要在 sql 中构建查询。我对少数情况进行了热编码。但当我思考时,越来越多的情况出现热编码可能非常耗时。有没有内置的库可以减轻我的工作?
最佳答案
您可以使用dateparser图书馆。
import dateparser
nl_dates = ["last week of july", " in june", "last month", "last n days"]
for nl_date in nl_dates:
res = dateparser.parse(nl_date)
if res:
print('"{}"": {}'.format(nl_date,res.date()))
" in june": 2019-06-12
"last month": 2019-05-12
该库将能够正确解决您的 4 个示例中的 2 个。此外,您可能会发现使用 NER(命名实体识别)模型很有帮助,spacy提供一:
import spacy
nlp = spacy.load("en_core_web_sm")
nl_dates = ["last week of july", " in june", "last month", "last 7 days"]
for nl_date in nl_dates:
doc = nlp(nl_date)
for entity in doc.ents:
print('{}: {}'.format(entity.label_, entity.text))
"DATE: last week"
"DATE: last month"
"DATE: last 7 days"
一般来说,当聊天机器人无法从文本中提取日期时,您可能希望聊天机器人以更易于检测的格式专门询问日期。
关于python - 如何从聊天机器人的输入文本中提取日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56489284/