我正在使用Python进行两个NLP项目,它们都有一个类似的任务,从句子中提取数值和比较运算符,如下所示:
"... greater than $10 ... ",
"... weight not more than 200lbs ...",
"... height in 5-7 feets ...",
"... faster than 30 seconds ... "我找到了两种不同的方法来解决这个问题:
我如何从这样的句子中解析数值?我想这是NLP中的一项常见任务。
所需的输出将类似于:
输入:
“大于10美元”
输出:
{'value': 10, 'unit': 'dollar', 'relation': 'gt', 'position': 3}发布于 2017-07-16 15:20:15
我可能会把它作为一个分块任务来处理,并将nltk的词性标记部分与其正则表达式块结合使用。这将允许您根据句子中单词的词性部分而不是基于单词本身来定义正则表达式。对于给定的句子,您可以这样做:
import nltk
# example sentence
sent = 'send me a table with a price greater than $100'我要做的第一件事是稍微修改你的句子,这样你就不会太混淆词性标签的部分。下面是一些您可以(使用非常简单的正则表达式)进行的更改的示例,但是您可以进行实验,看看是否还有其他的:
$10 -> 10 dollars
200lbs -> 200 lbs
5-7 -> 5 - 7 OR 5 to 7所以我们得到:
sent = 'send me a table with a price greater than 100 dollars'现在你可以从你的句子中得到词性的部分:
sent_pos = nltk.pos_tag(sent.split())
print(sent_pos)
[('send', 'VB'), ('me', 'PRP'), ('a', 'DT'), ('table', 'NN'), ('with', 'IN'), ('a', 'DT'), ('price', 'NN'), ('greater', 'JJR'), ('than', 'IN'), ('100', 'CD'), ('dollars', 'NNS')]现在,我们可以创建一个大块头,它将根据一个(相对)简单的正则表达式对POS标记的文本进行分块:
grammar = 'NumericalPhrase: {<NN|NNS>?<RB>?<JJR><IN><CD><NN|NNS>?}'
parser = nltk.RegexpParser(grammar)这定义了一个语法分析器,它可以对数字短语进行分块(我们称之为短语类型)。它将你的数字短语定义为:一个可选名词、一个可选副词、一个比较形容词、一个介词、一个数字和一个可选名词。这只是一个建议,你可能想如何定义你的短语,但我认为这将比使用正则表达式对单词本身简单得多。
要想得到你的短语,你可以:
print(parser.parse(sent_pos))
(S
send/VB
me/PRP
a/DT
table/NN
with/IN
a/DT
(NumericalPhrase price/NN greater/JJR than/IN 100/CD dollars/NNS)) 或者只得到你能做的短语:
print([tree.leaves() for tree in parser.parse(sent_pos).subtrees() if tree.label() == 'NumericalPhrase'])
[[('price', 'NN'),
('greater', 'JJR'),
('than', 'IN'),
('100', 'CD'),
('dollars', 'NNS')]]发布于 2022-10-28 21:25:09
https://spacy.io/universe/project/numerizer可能适用于您的用例。
从链接中:
from spacy import load
import numerizer
nlp = load('en_core_web_sm') # or any other model
doc = nlp('The Hogwarts Express is at platform nine and three quarters')
doc._.numerize()
# {nine and three quarters: '9.75'}https://stackoverflow.com/questions/45126071
复制相似问题