gpt4 book ai didi

python - NLTK:如何访问分块字符串

转载 作者:太空宇宙 更新时间:2023-11-03 15:40:11 26 4
gpt4 key购买 nike

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

这是我的输入

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

我想捕捉

67% rise12% fall

POS标记以上句子显示

('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

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

我怎样才能实现这个目标?

最佳答案

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

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

然后您可以将其推广到任何句子列表和词性标签。

关于python - NLTK:如何访问分块字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42206539/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com