12

我需要从 Python 的段落中解析句子。是否有现有的软件包可以做到这一点,还是我应该在这里尝试使用正则表达式?

4

2 回答 2

42

nltk.tokenize模块专为此设计并处理边缘情况。例如:

>>> from nltk import tokenize
>>> p = "Good morning Dr. Adams. The patient is waiting for you in room number 3."
>>> tokenize.sent_tokenize(p)
['Good morning Dr. Adams.', 'The patient is waiting for you in room number 3.']
于 2012-02-28T00:34:26.907 回答
0

这是我获得前 n 个句子的方法:

def get_first_n_sentence(text, n):
    endsentence = ".?!"
    sentences = itertools.groupby(text, lambda x: any(x.endswith(punct) for punct in endsentence))
    for number,(truth, sentence) in enumerate(sentences):
        if truth:
            first_n_sentences = previous+''.join(sentence).replace('\n',' ')
        previous = ''.join(sentence)
        if number>=2*n: break #

    return first_n_sentences

参考:http ://www.daniweb.com/software-development/python/threads/303844

于 2012-02-28T00:23:04.223 回答