To re or not to re ... ( word wrap function?)
Ignacio Vazquez-Abrams
ignacio at openservices.net
Fri Sep 21 18:37:49 EDT 2001
On Fri, 21 Sep 2001, Chris Barker wrote:
> I was just asked if it would be hard to write a script that would take
> the output from an MS word: "save as text" operation, and re-format it
> so it was wrapped to 80 character lines. I said it would be easy, then I
> thought about it and realised it was not quite as trivial as I thought.
> First I came up with a function that used a few string methods, but was
> mostly "by hand". Then I tried an re version. It turned out to be not
> much easier or shorter, though probably a little faster. I have not
> benchmarked it, and frankly, speed is of little concern here: I'm after
> elegance.
>
> Anyway, I figured that:
> A) someone else must have done this already
Yup. The following will do an entire document at once:
---
def wordwrap(text, width):
i=0
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
---
--
Ignacio Vazquez-Abrams <ignacio at openservices.net>
More information about the Python-list
mailing list