I am looking for a way to copy a txt file and modify it so that every sentence begins a new line.
I am very new to programming in Python and would like some help explaining how can I do this.
For example,
First sentence. Second. Third.
Should be
First sentence.
Second.
Third.
This is what I have so far:
f=open('a.txt')
f1=open('b.txt','a')
with open('a.txt', 'r') as file:
string = file.read().replace('.', '.\n')
with open('b.txt', 'w') as b:
b.write(string)
f1.close()
f.close()
This can be done using the replace method for strings. https://www.geeksforgeeks.org/python-string-replace/
Basically, you just tell it what you are wanting to replace (in this case punctuation at the end of a sentence) and what to replace it with (a new line).
string = 'First sentence. Second. Third.'
print(string)
string = string.replace(". ", ".\n")
print(string)
Consider using replace for? and. as well.
As for writing to the result file, after you have the modified text in your string variable:
with open("output_file.txt", "w") as output_file:
output_file.write(string)
The "w" parameter on open allows you to write to the file.
You first need to define what is a sentence for you. On this case, a sentence is separeted by '.', so you just need to imput:
a = "First sentence. Second. Third." print(a.replace(". ", ".\n"))
But if you will consider others caracteres, like ','? ';' and ','. you will also put those options too.
All code:
f = open("demofile.txt", "r")
print(f.read())
a = f.read()
print(a.replace(". ", ".\n"))
f = open("demofile2.txt", "a")
f.write(a.replace(". ", ".\n"))
text = "First sentence. Second. Third."
text = text.split(". ")
for x in range(0,len(text)):
if "." in text[x]:
text[x] = text[x][:-1]
print(text[x]+".")
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.