I have been provided a text splitter class that will take a text input and use re.sub to make replacements when matches are found and also splits sentences up and stores them in a list.
I had an idea to improve the code by storing the expressions in a list and iterating over the list and for each expression looking for a match in the given text. However different replacements are made depending on the expression so not sure how that would work.
What improvements could be made to the code to simplify it? Also am I missing any limitations to the code I could improve?
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|uk)"
digits = "([0-9])"
urls = "((http|https)\:\/\/)[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z]){2,6}([a-zA-Z0-9\.\&\/\?\:@\-_=#])*"
class TextSplitter:
@classmethod
def split_into_sentences(self, text):
text = " " + text + " "
text = text.replace("\n"," ")
for match in re.compile(urls).finditer(text):
text = text.replace(match.group(0), match.group(0).replace('.', '<prd>'))
text = re.sub(prefixes,"\\1<prd>",text)
text = re.sub(websites,"<prd>\\1",text)
text = re.sub(digits + "[.]" + digits,"\\1<prd>\\2",text)
if "Ph.D" in text: text = text.replace("Ph.D.","Ph<prd>D<prd>")
text = re.sub("\s" + alphabets + "[.] "," \\1<prd> ",text)
text = re.sub(acronyms+" "+starters,"\\1<stop> \\2",text)
text = re.sub(alphabets + "[.]" + alphabets + "[.]" + alphabets + "[.]","\\1<prd>\\2<prd>\\3<prd>",text)
text = re.sub(alphabets + "[.]" + alphabets + "[.]","\\1<prd>\\2<prd>",text)
text = re.sub(" "+suffixes+"[.] "+starters," \\1<stop> \\2",text)
text = re.sub(" "+suffixes+"[.]"," \\1<prd>",text)
text = re.sub(" " + alphabets + "[.]"," \\1<prd>",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("?\"","\"?")
# ellipses
for match in re.compile(r"(\.)(\.+)").finditer(text):
text = text.replace(match.group(0), (len(match.group(0)) * '<prd>') + '<stop>')
text = text.replace(".",".<stop>")
text = text.replace("?","?<stop>")
text = text.replace("!","!<stop>")
text = text.replace("<prd>",".")
sentences = text.split("<stop>")
sentences = [s.strip() for s in sentences]
sentences = [s for s in sentences if not len(s) == 0]
print(text)
print(sentences)
return sentences
text = "This is a test sentence! This is sentence two. I am sentence three?"
TextSplitter.split_into_sentences(text)
The code produces the following output:
This is a test sentence!<stop> This is sentence two.<stop> I am sentence three?<stop>
['This is a test sentence!', 'This is sentence two.', 'I am sentence three?']