【发布时间】:2016-03-24 22:44:56
【问题描述】:
我正在尝试使用 NLTK 的 POS 标签作为正则表达式来分块一个句子。根据句子中单词的标签,定义了2条规则来识别短语。
主要是,我想捕捉一个或多个动词后面跟着一个可选的限定词,然后是一个或多个名词的块。这是定义中的第一条规则。但它不会被捕获为短语块。
import nltk
## Defining the POS tagger
tagger = nltk.data.load(nltk.tag._POS_TAGGER)
## A Single sentence - input text value
textv="This has allowed the device to start, and I then see glitches which is not nice."
tagged_text = tagger.tag(textv.split())
## Defining Grammar rules for Phrases
actphgrammar = r"""
Ph: {<VB*>+<DT>?<NN*>+} # verbal phrase - one or more verbs followed by optional determiner, and one or more nouns at the end
{<RB*><VB*|JJ*|NN*\$>} # Adverbial phrase - Adverb followed by adjective / Noun or Verb
"""
### Parsing the defined grammar for phrases
actp = nltk.RegexpParser(actphgrammar)
actphrases = actp.parse(tagged_text)
分块器的输入,tagged_text 如下。
标记文本 出[7]: [('这个','DT'), ('有', 'VBZ'), ('允许', 'VBN'), ('the', 'DT'), ('设备', 'NN'), ('到','到'), ('开始','NNP'), ('和', '抄送'), ('我','PRP'), ('那么', 'RB'), ('见','VB'), ('故障','NNS'), ('哪个','WDT'), ('是','VBZ'), ('不是','RB'), ('nice.', 'NNP')]
在最终输出中,仅捕获匹配第二条规则的副词短语('then see')。 我希望口头短语('allowed the device')与第一条规则匹配并被捕获,但事实并非如此。
actphrases Out[8]: Tree('S', [('This', 'DT'), ('has', 'VBZ'), ('allowed', 'VBN'), ('the', 'DT'), ('device', 'NN'), ('to', 'TO'), ('start,', 'NNP'), ('and', 'CC'), ('I', 'PRP'), Tree('Ph', [('then', 'RB'), ('see', 'VB')]), ('glitches', 'NNS'), ('which', 'WDT'), ('is', 'VBZ'), ('not', 'RB'), ('nice.', 'NNP')])
使用的 NLTK 版本是 2.0.5 (Python 2.7) 任何帮助或建议将不胜感激。
提前致谢,
巴拉。
【问题讨论】:
-
首先将您的 NLTK 更新到 3.1。自 2.0 以来发生了重大变化,因此有必要获得工作代码。
sudo apt-get install python-nltk或sudo pip install -U nltk。那就看看stackoverflow.com/questions/34090734/…
标签: python regex nlp nltk text-chunking