2017-08-30 29 views
1

我正在研究一个简单的基于语法的分析器。为此,我需要首先标记输入。在我的文章中出现了很多城市(例如纽约,旧金山等)。当我使用标准的nltk word_tokenizer时,所有这些城市都会被拆分。NLTK标记化但不分割命名实体

from nltk import word_tokenize 
word_tokenize('What are we going to do in San Francisco?') 

电流输出:

['What', 'are', 'we', 'going', 'to', 'do', 'in', 'San', 'Francisco', '?'] 

所需的输出:

['What', 'are', 'we', 'going', 'to', 'do', 'in', 'San Francisco', '?'] 

我怎样才能令牌化这样的句子,不要拆开命名实体?

回答

2

识别的命名实体,然后步行结果和加入的分块的令牌一起:

>>> from nltk import ne_chunk, pos_tag, word_tokenize 
>>> toks = word_tokenize('What are we going to do in San Francisco?') 
>>> chunks = ne_chunk(pos_tag(toks)) 
>>> [ w[0] if isinstance(w, tuple) else " ".join(t[0] for t in w) for w in chunks ] 
['What', 'are', 'we', 'going', 'to', 'do', 'in', 'San Francisco', '?'] 

chunks每个元素可以是一个元组(word, pos)或含有该组块的份Tree()