我正在使用 nltk 将文本拆分为句子单元。但是,我需要将包含引号的句子提取为一个单元。现在,每个句子,即使它在引用中,也会被提取为一个单独的部分。
这是我尝试将其提取为单个单元的示例:
"This is a sentence. This is also a sentence," said the cat.
现在我有这个代码:
import nltk.data
tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
text = 'This is a sentence. This is also a sentence," said the cat.'
print '\n-----\n'.join(tokenizer.tokenize(text, realign_boundaries=True))
这工作得很好,但我想维护带有引号的句子,即使引号本身包含多个句子。
上面的代码产生:
This is a sentence.
-----
This is also a sentence," said the cat.
我试图将整个文本提取为一个单元:
"This is a sentence. This is also a sentence," said the cat.
有没有一种简单的方法可以使用 nltk 来做到这一点,或者我应该使用正则表达式?开始使用 nltk 的简单性给我留下了深刻的印象,但现在我陷入了困境。
如果我正确理解问题,那么这个正则表达式应该可以做到:
import re
text = '"This is a sentence. This is also a sentence," said the cat.'
for grp in re.findall(r'"[^"]*\."|("[^"]*")*([^".]*\.)', text):
print "".join(grp)
它是 2 个模式 or 的组合。第一个找到普通的引用句子。第二个查找普通句子或带有引号的句子,后跟句点。如果您有更复杂的句子,可能需要进一步调整。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)