NLP | Correct noun extraction



We can then test this against the first tagged sentence treebank_chunk, to compare the results with the previous recipe:

Code # 1: Testing by the first tag offer treebank_chunk

from nltk.corpus import treebank_chunk

from nltk.chunk import RegexpParser

from chunkers import sub_leaves

 

chunker = RegexpParser (r "" " 

NAME:

{& lt; NNP & gt; +}

"" " )

 

print ( " Named Entities: "

  sub_leaves (chunker.parse (

  treebank_chunk.tagged_sents () [ 0 ]), ` NAME` ))

Output:

 Named Entities: [[(`Pierre`,` NNP`), (`Vinken`,` NNP`)], [(`Nov .`, `NNP`)]] 

Note. The above code returns all native nouns — Pierre, Vinken, November. 
NAME chunker — this is a simple use of the RegexpParser class. All sequences of words marked with NNP are concatenated into NAME fragments. 
PersonChunker class can be used if you only want to separate the names of people.

Code # 2: PersonChunker class

from nltk.chunk import ChunkParserI

from nltk.chunk.util import conlltags2tree

from nltk. corpus import names

  

class PersonChunker (ChunkParserI):

  def __ init __ ( self ):

  self . name_set = set (names.words ())

  

  def parse ( self , tagged_sent):

 

iobs = []

in_person = False

for word, tag in tagged_sent:

if word in self . name_set and in_person:

iobs. append ((word, tag, `I-PERSON` ))

elif word in self . name_set:

iobs.append ((word, tag, `B-PERSON` ))

in_person = True

  else :

iobs.append ((word, tag, `O` ))

  in_person = False

 

  return conlltags2tree (iobs)

PersonChunker class checks if each word is in its names_set (generated from the name corpus) by iterating over the tag sentence ... It uses the tags I-BERSON or I-PERSON if the current word is in names_set, depending on whether the previous word was also in names_set. The IOB tag is assigned to a word that is not in the names_set argument. The IOB tag list is converted to a tree using conlltags2tree () upon completion.

Code # 3: Using the PersonChunker class in the same tag sentence

from nltk.corpus import treebank_chunk

from nltk.chunk import RegexpParser

from chunkers import sub_leaves

  

from chunkers import PersonChunker

chun ker = PersonChunker ()

print ( "Person name :"

sub_leaves (chunker.parse (

treebank_chunk.tagged_sents () [ 0 ]), `PERSON` ))

Output:

 Person name: [[(`Pierre`,` NNP`)]]