📜  python 句子拆分器 - Python 代码示例

📅  最后修改于: 2022-03-11 14:46:31.845000             🧑  作者: Mango

代码示例2
# -*- coding: utf-8 -*-
import re
alphabets= "([A-Za-z])"
prefixes = "(Mr|St|Mrs|Ms|Dr)[.]"
suffixes = "(Inc|Ltd|Jr|Sr|Co)"
starters = "(Mr|Mrs|Ms|Dr|He\s|She\s|It\s|They\s|Their\s|Our\s|We\s|But\s|However\s|That\s|This\s|Wherever)"
acronyms = "([A-Z][.][A-Z][.](?:[A-Z][.])?)"
websites = "[.](com|net|org|io|gov)"

def split_into_sentences(text):
    text = " " + text + "  "
    text = text.replace("\n"," ")
    text = re.sub(prefixes,"\\1",text)
    text = re.sub(websites,"\\1",text)
    if "Ph.D" in text: text = text.replace("Ph.D.","PhD")
    text = re.sub("\s" + alphabets + "[.] "," \\1 ",text)
    text = re.sub(acronyms+" "+starters,"\\1 \\2",text)
    text = re.sub(alphabets + "[.]" + alphabets + "[.]" + alphabets + "[.]","\\1\\2\\3",text)
    text = re.sub(alphabets + "[.]" + alphabets + "[.]","\\1\\2",text)
    text = re.sub(" "+suffixes+"[.] "+starters," \\1 \\2",text)
    text = re.sub(" "+suffixes+"[.]"," \\1",text)
    text = re.sub(" " + alphabets + "[.]"," \\1",text)
    if "”" in text: text = text.replace(".”","”.")
    if "\"" in text: text = text.replace(".\"","\".")
    if "!" in text: text = text.replace("!\"","\"!")
    if "?" in text: text = text.replace("?\"","\"?")
    text = text.replace(".",".")
    text = text.replace("?","?")
    text = text.replace("!","!")
    text = text.replace("",".")
    sentences = text.split("")
    sentences = sentences[:-1]
    sentences = [s.strip() for s in sentences]
    return sentences