1

我正在使用 NLTK 分块,我想捕获与我的规则匹配的字符串。例如

这是我的输入

The stocks show 67% rise, last year it was 12% fall

我想捕捉

67% rise12% fall

POS Tagging 上面这句话显示

('The', 'DT'), ('stocks', 'NNS'), ('show', 'VBP'), ('67', 'CD'), ('%', 'NN'), ('rise', 'NN'), (',', ','), ('last', 'JJ'), ('year', 'NN'), ('it', 'PRP'), ('was', 'VBD'), ('12', 'CD'), ('%', 'NN'), ('fall', 'NN')

现在,我想出了一个简单的规则

Stat: {<CD><NN>(<NN>+|<VBN>|JJ)?}

效果很好并且可以捕获

('67', 'CD'), ('%', 'NN'), ('rise', 'NN')

('12', 'CD'), ('%', 'NN'), ('fall', 'NN')

现在,我想提取捕获的确切字符串。所以,我想要

67% rise12% fall

我试过

current=[]
for word,tag in subtree.leaves():
    current.append(word)
print ' '.join(current)

但我明白了

67 % rise12 % fall

注意%数字之间的空格。这在逻辑上是正确的,但不是所需的输出。我想要确切的字符串,因为我想知道捕获的字符串的开始和结束索引。

我怎样才能做到这一点?

4

1 回答 1

1

(可怕的hacky)对于您的示例字符串和标签:

s = ('The', 'DT'), ('stocks', 'NNS'), ('show', 'VBP'), ('67', 'CD'), ('%', 'NN'), ('rise', 'NN'), (',', ','), ('last', 'JJ'), ('year', 'NN'), ('it', 'PRP'), ('was', 'VBD'), ('12', 'CD'), ('%', 'NN'), ('fall', 'NN')
a = (('67', 'CD'), ('%', 'NN'), ('rise', 'NN'))
c = 'The stocks show 67% rise, last year it was 12% fall'

编辑:作为列表理解:

>>>c[min((c.index(i[0]) for i in a)):max((c.index(i[0]) for i in a)) + [len(i[0]) for i in a][-1]]
>>>'67% rise'

找出每个单词在输入句子中出现的位置。记录每个单词的长度。

检查您想要的词性标签在您的例句中的位置。(编辑:如果不需要,则删除)

position=[]
lengths=[]

for wordtag in a:
    print wordtag,c.index(i[0]),wordtag[0],len(wordtag[0])
    position.append(c.index(wordtag[0]))
    lengths.append(len(wordtag[0]))

> ('67', 'CD') 16 67 2
> ('%', 'NN') 18 % 1
> ('rise', 'NN') 20 rise 4

print position
print lengths

> [16, 18, 20]
> [2, 1, 4]

根据所需标签的最小和最大位置对输入句子进行切片。您添加一个lengths[-1]以添加单词的长度rise

valid = c[min(position):max(position) + lengths[-1]]
print valid

> [16, 18, 20]
> [2, 1, 4]

> 67% rise

然后,您可以将其概括为任何句子列表和词性标签。

于 2017-02-13T15:31:39.217 回答