Justifying text.

John Roth johnroth at ameritech.net
Sun Sep 30 14:39:20 CEST 2001


"A.A" <andtherewaswater at yahoo.com> wrote in message
news:3BB6D7EE.D87FAF00 at yahoo.com...
> I've really messed up: IN short, I just wanted to write a program in
> python that justified plain text in a .txt to a specified margin.

Justification is not difficult. There are a number of approaches, depending
on what you want to do. If the text is already properly split into
lines, see the .ljust, .rjust and .center string methods. If it isn't,
then you need to break it into lines. There may be easier methods,
but I use a simple loop, scanning backwards from the maximum
line length until I hit white space.

The following may do what you want:

<begin program>
# translate MS Word text format with no line breaks to 80 character
# line output. Each paragraph is presumed to be a single input line.

import sys

def ltDriver(fnIn, fnOut):
    inFile = open(fnIn, "r")
    outFile = open(fnOut, "w")
    for line in inFile.readlines():
        i = 0
        if line[-1] == '\n': line = line[:-1] + " "
        while i < len(line):
            j = min(i + 80, len(line) - 1)
            while j > i and not line[j].isspace(): j -= 1
            while j > i and line[j].isspace(): j -= 1
            outFile.write(line[i:j+1] + "\n")
            i = j + 1
            while i < len(line) and line[i].isspace(): i += 1

if __name__ == "__main__":
    ltDriver("B1I14Attack.txt", "B1I14Attack2.txt")


</end program>

John Roth







More information about the Python-list mailing list