Reputation:
Struggling with how to add a new line for every 5th sentence in a long text string.
Input example
text = 'The puppy is cute. Summer is great. Happy Friday. Sentence4. Sentence5. Sentence6. Sentence7.
Desired output:
The puppy is cute. Summer is great. Happy friday. Sentence4. Sentence5.
Sentence6. Sentence7.
Can anyone help with this?
Upvotes: 0
Views: 1782
Reputation: 15268
Using regular expression. Add \n after 5 matches of "[not .] followed by .".
import re
text = 'The puppy is cute. Summer is great. Happy friday. sentence4. sentence5. sentence6. sentence7.'
print(re.sub(r'((?:[^.]+\.\s*){5})',r'\1\n',text))
A more advanced regex sentence matcher that handles abbreviations and other punctuation, by matching on ending punctuation.
Reference: https://mikedombrowski.com/2017/04/regex-sentence-splitter/
Note: there are still edge cases that this fails on, such as T.V. followed by Mr. needs double spaces to denote a separate sentence. Quotations with sentences in them will be split up. etc.
import re
sentence_regex = r'((.*?([\.\?!][\'\"\u2018\u2019\u201c\u201d\)\]]*\s*(?<!\w\.\w.)(?<![A-Z][a-z][a-z]\.)(?<![A-Z][a-z]\.)(?<![A-Z]\.)\s+)){5})'
text = 'The puppy is cute. Watch T.V. Mr. Summers is great. Say "my name." My name is. Or not... Happy friday? Sentence4. Sentence5. Sentence6. Sentence7.'
text += " " + text
print(re.sub(sentence_regex,r'\1\n',text))
Anything more complex than this you may want to look into a language processing toolkit.
Upvotes: 2
Reputation: 66
Here is a simple function that adds a newline to the end of 5th sentence
def new_line(sentence: str):
# characters that mark the end of a sentence
end_of_sentence_markers = ['.', '!', '?', '...']
# after n sentences insert new_line
n = 5
# keeps track
count = 0
# final string as list for efficiency
final_str = []
# split at space
sentence_split = sentence.split(' ')
# traverse the sentence split
for word in sentence_split:
# if end of sentence is present then increase count
if word[-1] in end_of_sentence_markers:
count += 1
# if count is equal to n then add newline otherwise add space
if count == n:
final_str.append(word + '\n')
count = 0
else:
final_str.append(word + ' ')
# return the string version of the list
return ''.join(final_str)
Here is a modified version:
def new_line_better(sentence: str, n: int):
# final string as list for efficiency
final_str = []
# split at period and remove extra spaces
sentence_split = list( map( lambda x : x.strip(), sentence.split('.') ) )
# pop off last space
sentence_split.pop()
# keeps track
count = 0
# traverse the sentences
for sentence in sentence_split:
count += 1
if count == n:
count = 0
final_str.append(sentence+'.\n')
else:
final_str.append(sentence+'. ')
# return the string version of the list
return ''.join(final_str)
Upvotes: 1
Reputation: 347
With list comprehension
text = 'The puppy is cute. Summer is great. Happy friday. sentence4. sentence5. sentence6. sentence7.'
lines = text.split(".")
result = ".".join([l if i % 5 else "\n"+l for (i, l) in enumerate(lines)]).lstrip()
print(result)
Upvotes: 0
Reputation: 3598
Another approach:
text = 'The puppy is cute. Summer is great. Happy friday. sentence4. sentence5. sentence6. sentence7.'
out = ''
for i, e in enumerate(text.split(".")):
if (i > 0) & (i % 5 == 0):
out = out + '\n'
out = out + e + '.'
out
result:
'The puppy is cute. Summer is great. Happy friday. sentence4. sentence5.\n sentence6. sentence7..'
Upvotes: 0
Reputation:
Try this:
text = 'The puppy is cute. Summer is great. Happy friday. sentence4. sentence5. sentence6. sentence7.'
splittext = text.split(".")
for x in range(5, len(splittext), 5):
splittext[x] = "\n"+splittext[x].lstrip()
text = ".".join(splittext)
print(text)
Upvotes: 3