Formatting a string to be a columned block of text

placid Bulkan at gmail.com
Tue Dec 26 07:52:30 EST 2006


Leon wrote:
> Hi,
>
> I'm creating a python script that can take a string and print it to the
> screen as a simple multi-columned block of mono-spaced, unhyphenated
> text based on a specified character width and line hight for a column.
> For example, if i fed the script an an essay, it would format the text
> like a newspaper on the screen. Text processing is very new to me, any
> ideas on how I could achieve a multi-columned text formatter. Are there
> any libraries that already do this?
>
> Thanks and happy holidays!
> Leon

I did something similar, read in text file format it to 79 characters
and print it out to a multiple images of 480x272 so i could read them
on my PSP. Anyway the code to handle the formatting (even though this
is one column of 78 characters with one character space from the top
and bottom, and sides)

corpus = open("essay.txt","r")

wordcount = 0
pctline = ""
pctlines = [

for line in corpus.readlines():
    # i dont need the newline character as it will be printed onto
images
    line = line[:-1]

    # i want individual words where each word is separated by a space
character
    words = line.split(" ")

    for word in words:
        if wordcount + len(word) + 1 < 78:
            wordcount =  wordcount + len(word) + 1
            pctline = pctline + word + " "
        else:
            wordcount = len(word)

            pctlines.append(pctline)
            pctline = None
            pctline = word + " "

corpus.close()

what it does is keeps a list of words and iterate through it and see if
the length of that word and one space character and the line doesn't
exceed 78, if it doesnt then add it to the pctlines, add the count to
the wordcount + 1. If it does then we have one line either 78
characters long or less and add it to pctlines which is a list of all
the lines.

Hope this helps.
Cheers




More information about the Python-list mailing list