如何从词性标记句中提取具有多种模式的语块?

2024-10-04 11:35:09 发布

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

给定一个使用nltk中的pos_标记函数进行pos标记的输入句子:

[('Veer','NNP'), ('Singh','NNP'), ('Rathore','NNP'), (“拍卖”、“VBD”), (“his”、“PRP$”), (‘巨人’、‘JJ’), ('house','NN'), (‘in’、‘in’), (‘新’、‘NNP’), ('York','NNP'), (“,”)]

我需要提取遵循某种模式的短语。例如,“NNP NNP”或“JJ NN”。 我们可能要提取的模式可能有“n”个。例如,这里我们需要两种模式,即“NNP NNP”和“JJ NN”

我希望上面输入的句子的输出是一个短语列表,如:

输出:

['Veer Singh Rathore', 'gigantic house', 'New York']

我试过这样的方法:

> grammar = (''' Chunk:{<JJ><NN>|<NNP>+<NNP>} ''')
> 
> def pos_and_chunking(question):
>     words = word_tokenize(question)
>     pos_words = pos_tag(words)
>     chunkParser = RegexpParser(grammar)
>     chunked_phrases = chunkParser.parse(pos_words)
>     chunked_phrases.draw()
>     for subtree in chunked_phrases.subtrees():
>         print(subtree)

但是我得到的输出是一棵树的形式

输出:

(S (Chunk Veer/NNP Singh/NNP Rathore/NNP) auctioned/VBD his/PRP$ (Chunk gigantic/JJ house/NN) in/IN (Chunk New/NNP York/NNP) ./.) (Chunk Veer/NNP Singh/NNP Rathore/NNP) (Chunk gigantic/JJ house/NN) (Chunk New/NNP York/NNP) enter image description here

如何解决这个问题

我将此链接用于分块: https://www.codespeedy.com/chunking-rules-in-nlp/


Tags: inposnew模式nnhousewordsyork