【问题标题】:Splitting sentences with nltk while preserving quotes在保留引号的同时使用 nltk 拆分句子
【发布时间】:2013-11-24 20:37:01
【问题描述】:

我正在使用 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 的简单程度给我留下了深刻的印象,但现在卡住了。

【问题讨论】:

  • 你使用的是哪个分词器?

标签: python regex python-2.7 nltk


【解决方案1】:

如果我正确理解了这个问题,那么这个正则表达式应该可以做到:

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 种模式的组合或组合在一起。第一个找到普通的引用句子。第二个查找普通句子或带有引号后跟句号的句子。如果您有更复杂的句子,可能需要进一步调整。

【讨论】:

    【解决方案2】:

    只需将您的打印语句更改为:

    print ' '.join(tokenizer.tokenize(text, realign_boundaries=True))
    

    这将用空格而不是\n-----\n连接句子。

    【讨论】:

    • 重点是拆分文本中的句子,除了引号中的句子。 ' '.join 将加入引号内/外的所有句子。
    • 谢谢,我试图澄清一下这个问题。我希望它现在更有意义。
    猜你喜欢
    • 1970-01-01
    • 2011-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多