Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

python - NLTK - Chunk grammar doesn't read commas

from nltk.chunk.util import tagstr2tree
from nltk import word_tokenize, pos_tag
text = "John Rose Center is very beautiful place and i want to go there with Barbara Palvin. Also there are stores like Adidas ,Nike ,Reebok Center."
tagged_text = pos_tag(text.split())

grammar = "NP:{<NNP>+}"

cp = nltk.RegexpParser(grammar)
result = cp.parse(tagged_text)

print(result)

Output:

(S
  (NP John/NNP Rose/NNP Center/NNP)
  is/VBZ
  very/RB
  beautiful/JJ
  place/NN
  and/CC
  i/NN
  want/VBP
  to/TO
  go/VB
  there/RB
  with/IN
  (NP Barbara/NNP Palvin./NNP)
  Also/RB
  there/EX
  are/VBP
  stores/NNS
  like/IN
  (NP Adidas/NNP ,Nike/NNP ,Reebok/NNP Center./NNP))

The grammar i use for chunking only works on nnp tags but if words are sequential with commas they will still on the same line.I want my chunk like this:

(S
  (NP John/NNP Rose/NNP Center/NNP)
  is/VBZ
  very/RB
  beautiful/JJ
  place/NN
  and/CC
  i/NN
  want/VBP
  to/TO
  go/VB
  there/RB
  with/IN
  (NP Barbara/NNP Palvin./NNP)
  Also/RB
  there/EX
  are/VBP
  stores/NNS
  like/IN
  (NP Adidas,/NNP)
  (NP Nike,/NNP)
  (NP Reebok/NNP Center./NNP))

What should i write in the "grammar=" or can i edit the output like i wrote above?As you can see i only parse proper nouns for my named entity project pls help me out.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use word_tokenize(string) instead of string.split():

>>> import nltk
>>> from nltk.chunk.util import tagstr2tree
>>> from nltk import word_tokenize, pos_tag
>>> text = "John Rose Center is very beautiful place and i want to go there with Barbara Palvin. Also there are stores like Adidas ,Nike ,Reebok Center."
>>> tagged_text = pos_tag(word_tokenize(text))
>>> 
>>> grammar = "NP:{<NNP>+}"
>>> 
>>> cp = nltk.RegexpParser(grammar)
>>> result = cp.parse(tagged_text)
>>> 
>>> print(result)
(S
  (NP John/NNP Rose/NNP Center/NNP)
  is/VBZ
  very/RB
  beautiful/JJ
  place/NN
  and/CC
  i/NN
  want/VBP
  to/TO
  go/VB
  there/RB
  with/IN
  (NP Barbara/NNP Palvin/NNP)
  ./.
  Also/RB
  there/EX
  are/VBP
  stores/NNS
  like/IN
  (NP Adidas/NNP)
  ,/,
  (NP Nike/NNP)
  ,/,
  (NP Reebok/NNP Center/NNP)
  ./.)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...