I have a text file with 1000 sentences. I splitted the sentences from '.' but there are also '?' and '!' available in those sentences. I need to split them as well and also join those characters at the end of those sentences. eg: text = "I have a friend. I have many friends. I am very happy today?Are you happy. I wish you were." Output:
I have a friend.
I have many friends!
I am very happy today.
Are you happy?
I wish you were.
The code I've tried is
textsentences = text.split('.')
I have tried this code.
with open("file.txt",'w') as writefile:
for line in textsentences:
line = line.strip()
writefile.write("%s . \n" % line)
It works only for one character.
This should work. The line_start
variable is to avoid unnecessary spaces at beginning of the sentence:
text = "I have a friend. I have many friends! I am very happy today. Are you happy? I wish you were."
line_start = False
with open("file.txt", 'w') as writefile:
for i in range(len(text)):
if text[i].isalnum() or text[i] == ' ':
if line_start == True and text[i] == ' ':
line_start = False
continue
writefile.write(text[i])
else:
writefile.write(text[i] +'\n')
line_start = True
Output: file.txt
I have a friend.
I have many friends!
I am very happy today.
Are you happy?
I wish you were.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.