我试图使用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)
输入到chunker,tagged_text如下所示。在
tagged_text Out[7]: [('This', 'DT'), ('has', 'VBZ'), ('allowed', 'VBN'), ('the', 'DT'), ('device', 'NN'), ('to', 'TO'), ('start,', 'NNP'), ('and', 'CC'), ('I', 'PRP'), ('then', 'RB'), ('see', 'VB'), ('glitches', 'NNS'), ('which', 'WDT'), ('is', 'VBZ'), ('not', 'RB'), ('nice.', 'NNP')]
在最后的输出中,只捕获与第二条规则相匹配的副词短语('然后参见“)。 我希望动词短语('允许设备)与第一条规则相匹配,也能被捕获,但事实并非如此。在
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(Python2.7) 任何帮助或建议将不胜感激。在
提前谢谢你
巴拉。在
关闭,但对正则表达式的微小更改将获得所需的输出。当您想使用},例如,}:
RegexpParser
语法获得通配符时,应该使用.*
而不是{VB.*
而不是{请注意,您捕获的是}。因此,在这个场景中,语法中的通配符(即“AdvP:{}”“”)将被忽略。在
Tree(AdvP, [('then', 'RB'), ('see', 'VB')])
,因为这些标记正好是RB
和{另外,如果是两种不同类型的短语,最好使用两个标签而不是一个。而且(我认为)通配符后面的字符串结尾有点多余,所以最好:
^{pr2}$相关问题 更多 >
编程相关推荐