Theiling Online    Sitemap    Conlang Mailing List HQ   

CHAT: Wordwrapping (was: File converter)

From:Boudewijn Rempt <bsarempt@...>
Date:Friday, November 12, 1999, 8:17
On Thu, 11 Nov 1999, FFlores wrote:

> > While you're at it, do you know, or have you made a program that can > word-wrap text (not on screen, but actually inserting line breaks)? > It should be easy, but I've tried with VBA and the resulting program > somehow mangles the output in one way or another every time! >
It is quite easy: look at the following. There might be a better, shorter and more pythonic way of doing it, but this works, is clear and not too slow. #!/usr/bin/env python import string import sys def wrap(text, length=67): words=string.split(text) # chop text into words line = "" text2= "" for word in words: if len(line +" "+ word) >= length: text2=text2+line+"\n" line=word else: line=line + " " + word return text2 + line if __name__=="__main__": if len(sys.argv) == 1: print "Usage: text linelength" elif len(sys.argv) == 2: print wrap(open(sys.argv[1]).read()) else: print wrap(open(sys.argv[1]).read(), int(sys.argv[2])) Of course, there are lots of special cases this thimble of bytes doesn't take into account, like paragraphs separated by \n\n, indenting and so on - but if that's needed, I use _fmt_ ;-), if necessary from my own programs. Boudewijn Rempt |