Python - 块和缝隙


分块是根据单词的性质将相似单词分组在一起的过程。在下面的示例中,我们定义了生成块所必须使用的语法。语法建议创建块时将遵循的名词和形容词等短语的顺序。块的图形输出如下所示。

import nltk

sentence = [("The", "DT"), ("small", "JJ"), ("red", "JJ"),("flower", "NN"), 
("flew", "VBD"), ("through", "IN"),  ("the", "DT"), ("window", "NN")]
grammar = "NP: {?
*}" cp = nltk.RegexpParser(grammar) result = cp.parse(sentence) print(result) result.draw()

当我们运行上面的程序时,我们得到以下输出 -

chunk_1.PNG

更改语法,我们得到不同的输出,如下所示。

import nltk

sentence = [("The", "DT"), ("small", "JJ"), ("red", "JJ"),("flower", "NN"),
 ("flew", "VBD"), ("through", "IN"),  ("the", "DT"), ("window", "NN")]

grammar = "NP: {
?*}" chunkprofile = nltk.RegexpParser(grammar) result = chunkprofile.parse(sentence) print(result) result.draw()

当我们运行上面的程序时,我们得到以下输出 -

chunk_2.PNG

钦金

Chinking 是从块中删除一系列标记的过程。如果标记序列出现在块的中间,则这些标记将被删除,在它们已经存在的位置留下两个块。

import nltk

sentence = [("The", "DT"), ("small", "JJ"), ("red", "JJ"),("flower", "NN"), ("flew", "VBD"), ("through", "IN"),  ("the", "DT"), ("window", "NN")]

grammar = r"""
  NP:
    {<.*>+}         # Chunk everything
    }+{      # Chink sequences of JJ and NN
  """
chunkprofile = nltk.RegexpParser(grammar)
result = chunkprofile.parse(sentence) 
print(result)
result.draw()

当我们运行上面的程序时,我们得到以下输出 -

中国佬.PNG

正如您所看到的,符合语法标准的部分作为单独的块从名词短语中被省略。这种提取不在所需块中的文本的过程称为“chinking”。