To re or not to re ... ( word wrap function?)

Boyd Roberts boyd at insultant.net
Fri Sep 21 19:38:01 EDT 2001


"Ignacio Vazquez-Abrams" <ignacio at openservices.net> a écrit dans le message news:
mailman.1001111905.15419.python-list at python.org...
> On Fri, 21 Sep 2001, Chris Barker wrote:
> > A) someone else must have done this already

yup, unix's fmt(1).

treat the input as a list of word and output the word if it'll fit
on the line, otherwise a newline, loop.  by list i don't mean turn
each line into a list, i mean treat the document conceptually as if
it was a list.

if your word is longer than 80 chars you will have to re-think this
strategy or at least code for this possible eventuality.  admittedly
it's unlikely to be a 'word' in any human language sense, but you have
to be able to deal with being handed any random chunk of bytes.

i'm not sure who did it, but there was a test done on handing arbitrary
files to unix text filters.  many of them dumped core.

> Yup. The following will do an entire document at once:
>
> ---
> def wordwrap(text, width):

i hope you have small documents or a _large_ amount or ram;  your
solution will not scale.

>   while i<len(text):
>     if i+width+1>len(text):
>       i=len(text)
>     else:
>       findnl=string.find(text, '\n', i)
>       findspc=string.rfind(text, ' ', i, i+width+1)
>       if findspc!=-1:
>         if findnl!=-1 and findnl<findspc:
>           i=findnl+1
>         else:
>           text=text[:findspc]+'\n'+text[findspc+1:]
>           i=findspc+1
>       else:
>         findspc=string.find(text, ' ', i)
>         if findspc!=-1:
>           text=text[:findspc]+'\n'+text[findspc+1:]
>           i=findspc+1
>   return text






More information about the Python-list mailing list