准确分句

2024-04-18 08:21:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我的程序接受一个文本文件,并使用split('.')将每个句子拆分为一个列表,这意味着当它注册一个句号时,它将被拆分,但是它可能不准确。在

例如

str='i love carpets. In fact i own 2.4 km of the stuff.'

输出

listOfSentences = ['i love carpets', 'in fact i own 2', '4 km of the stuff']

期望输出

^{pr2}$

我的问题是:如何分割句子的结尾而不是每个句号。


Tags: ofthe程序列表句子splitfact文本文件
3条回答

我发现https://github.com/fnl/syntok/相当不错,实际上是所有流行歌曲中最好的。具体来说,我在英语新闻文章中测试了nltk(punkt)、spacy和syntok。在

import syntok.segmenter as segmenter

document = "some text. some more text"

for paragraph in segmenter.analyze(document):
    for sentence in paragraph:
        for token in sentence:
            # exactly reproduce the input
            # and do not remove "imperfections"
            print(token.spacing, token.value, sep='', end='')
    print("\n")  # reinsert paragraph separators

如果你的句子都以“和”结尾,可以尝试regex:

import re

text = "your text here. i.e. something."
sentences = re.split(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?)\s', text)

来源:Python - RegEx for splitting text into sentences (sentence-tokenizing)

任何基于regex的方法都不能处理诸如“我看到了Smith先生。”,并且为这些情况添加黑客是不可伸缩的。正如userest评论的那样,任何严肃的实现都会使用数据。在

如果您只需要掌握英语,那么spaCy比NLTK更好:

from spacy.en import English
en = English()
doc = en(u'i love carpets. In fact i own 2.4 km of the stuff.')
for s in list(doc.sents):
    print s.string

更新:spaCy现在支持多种语言。在

相关问题 更多 >