Drew Drew - 1 month ago 11
Python Question

Copying a text file into a list paragraph by paragraph in Python

I'm writing a code that takes a long text file, formats each paragraph in a certain way and prints out the output to the console. I've come up with different ways to do this but they're all really long and bulky. I just wanted to know if there was a command or something that could do this. Maybe a modified version of the

.format()
or a
re
command. Thank you

The text looks like this:

diffindere. 3. Et adhuc singulorum supplicia narro: quid si tibi
libuerit, relictis in quos ira uiritim exarsit, aspicere caesas gladio
contiones et plebem inmisso milite contrucidatam et in perniciem
promiscuam totos populos capitis damna

4.tamquam aut curam nostram deserentibus aut auctoritatem
contemnentibus. Quid? gladiatoribus quare populus irascitur, et tam
inique ut iniuriam putet quod non libenter pereunt? contemni se
iudicat et uultu gestu ardore ex spectatore in aduersarium uertitur.


The out put would depend on how I format it but everything remains in paragraphs. For example, I could format it by replacing all commas with full stops then the out put would be this:

diffindere. 3. Et adhuc singulorum supplicia narro: quid si tibi
libuerit. relictis in quos ira uiritim exarsit. aspicere caesas gladio
contiones et plebem inmisso milite contrucidatam et in perniciem
promiscuam totos populos capitis damna

4.tamquam aut curam nostram deserentibus aut auctoritatem
contemnentibus. Quid? gladiatoribus quare populus irascitur. et tam
inique ut iniuriam putet quod non libenter pereunt? contemni se
iudicat et uultu gestu ardore ex spectatore in aduersarium uertitur.

Answer

@ Blank line is made of new line, no text and then new line, so practically \n\n.

Use the .split method:

par = open('file.txt').read().split('\n\n')

Will store the paragraphs (splitted by newlines) as an array of strings inside par.

Then you can process these paragraph, and later join them back:

text = '\n\n'.join(par)