Skip to main content
 首页 » 编程设计

python之NLTK RegexpParser,通过精确匹配一个项目来分块短语

2024年10月17日29txw1958

我正在使用 NLTK 的 RegexpParser 来分块名词短语,我用语法将其定义为

 grammar = "NP: {<DT>?<JJ>*<NN|NNS>+}" 
 cp = RegexpParser(grammar) 

这很好,它匹配一个名词短语作为:

  • DT 如果存在
  • JJ 任意数
  • NN 或 NNS,至少一个

现在,如果我想匹配相同但将 JJ 的任何数字 转换为只有一个 怎么办?所以我想匹配DT如果存在,一个 JJ和1+ NN/NNS。如果有多个 JJ,我只想匹配其中一个,最接近名词的那个(如果有 DT,还有 NN/NNS)。

语法

grammar = "NP: {<DT>?<JJ><NN|NNS>+}" 

只有当只有一个JJ,语法才会匹配

grammar = "NP: {<DT>?<JJ>{1}<NN|NNS>+}" 

考虑到 typical Regexp patterns,我认为这会起作用, 引发 ValueError。

例如,在“This beautiful green skirt”中,我想分块“This green skirt”。

那么,我该如何进行呢?

请您参考如下方法:

语法 grammar = "NP: {<DT>?<JJ><NN|NNS>+}"对于您提到的要求是正确的。

你在评论部分给出的例子,你没有在输出中得到 DT -

"This beautiful green skirt is for you." 
 
Tree('S', [('This', 'DT'), ('beautiful', 'JJ'), Tree('NP', [('green','JJ'),  
('skirt', 'NN')]), ('is', 'VBZ'), ('for', 'IN'), ('you', 'PRP'), ('.', '.')]) 

在您的示例中,有 2 consecutive JJs这不符合您所说的要求 - "I want to match DT if it exists, one JJ and 1+ NN/NNS."


更新要求 - I want to match DT if it exists, one JJ and 1+ NN/NNS. If there are more than one JJ, I want to match only one of them, the one nearest to the noun (and DT if there is, and NN/NNS).

在这里,你将需要使用

grammar = "NP: {<DT>?<JJ>*<NN|NNS>+}" 

并对 NP block 进行后处理以去除多余的 JJ。

代码:

from nltk import Tree 
 
chunk_output = Tree('S', [Tree('NP', [('This', 'DT'), ('beautiful', 'JJ'), ('green','JJ'), ('skirt', 'NN')]), ('is', 'VBZ'), ('for', 'IN'), ('you', 'PRP'), ('.', '.')]) 
 
for child in chunk_output: 
    if isinstance(child, Tree):                
        if child.label() == 'NP': 
            for num in range(len(child)): 
                if not (child[num][1]=='JJ' and child[num+1][1]=='JJ'): 
                    print child[num][0] 

输出:

This 
green 
skirt