text wrapping help

R

Ryan K

I'm trying to text wrap a string but not using the textwrap module. I
have 24x9 "matrix" and the string needs to be text wrapped according
to those dimensions. Is there a known algorithm for this? Maybe some
kind of regular expression? I'm having difficulty programming the
algorithm. Thanks,
Ryan
 
R

Ryan K

Okay, I was a little vague in my last post...the matrix is like a
Wheel of Fortune board and it knows nothing about newlines. After 24
characters it spills over onto the next line. Here is what I came up
with:

<pre>
## Wrap Text

def wrap_text(in_str, chars_line):
""" wrap text """
spaces = 0
new_str = ""
tmp_str = ""
while True:
tmp_str = in_str[:chars_line]
if tmp_str[chars_line-1].isspace():
new_str += tmp_str
else:
spaces = 0
for ch in reversed(tmp_str):
if ch.isspace():
break
spaces += 1
tmp_str = tmp_str[:chars_line-spaces]
tmp_str += " " * spaces
new_str += tmp_str
in_str = in_str[chars_line-spaces:]
if len(in_str) <= chars_line:
new_str += " " + in_str
break
return new_str


if __name__ == '__main__':

sample_text = """Personal firewall software may warn about the
connection IDLE makes to its subprocess using this computer's internal
loopback interface. This connection is not visible on any external
interface and no data is sent to or received from the Internet."""
print wrap_text(sample_text, 24)

</pre>

It doesn't even run but when I go through it interactively it seems
okay. Once again, any help is appreciated.
 
A

attn.steven.kuo

I'm trying to text wrap a string but not using the textwrap module. I
have 24x9 "matrix" and the string needs to be text wrapped according
to those dimensions. Is there a known algorithm for this? Maybe some
kind of regular expression? I'm having difficulty programming the
algorithm.


Try:

import re
sample_text = """Personal firewall software may warn about the
connection IDLE makes to its subprocess using this computer's internal
loopback interface. This connection is not visible on any external
interface and no data is sent to or received from the Internet."""

# assume 24 is sufficiently wide:

lines = map(lambda x: x.rstrip(),
re.findall(r'.{1,24}(?:(?<=\S)\s|$)', sample_text.replace("\n", " ")))

print "\n".join(lines)
 
R

Ryan K

That works great but I need to replace the newlines with 24-(the index
of the \n) spaces.
 
A

attn.steven.kuo

That works great but I need to replace the newlines with 24-(the index
of the \n) spaces.



Just left-justify to the appropriate width with
the the padding character you wanted:

equally_long_lines = map(lambda x: x.ljust(24, ' '), lines)

print "\n".join(equally_long_lines)
 
B

Bjoern Schliessmann

Ryan said:
It doesn't even run but when I go through it interactively it
seems okay. Once again, any help is appreciated.

I haven't tested yet, but why don't you make a list of words of the
text (with split), and then accumulate words in a list until the
next word would make the line too long. Then just join the word
list, fill with spaces until line end and start over.

Regards,


Björn
 
D

Dennis Lee Bieber

For continuity purposes as the original message had been sent via
email...

-=-=-=-=-=-=-=-
Forgive my going direct -- I do not have news posting ability
from work, and won't be home for another three hours. Replies have been
directed to my home address. Once home, I'll post a copy of this message
on the group itself, just for completeness…

Try

"""
Simple procedure to produce space-filled text strings
(left, right, center) for display devices that do not use
new-line control, but instead treat the output as a
single line of data

stripping leading spaces of follow-up lines when left justified
is left as an exercise
"""

LEFTJUST = 1
CENTERED = 2
RIGHTJUST = 3

def fillWrap(text, width=24, mode=LEFTJUST):
output = []
text = " ".join(text.split()) #clean up embedded white space
while text:
if len(text) > width:
(line, text) = (text[:width], text[width:])
spc = line.rfind(" ")
if spc != -1: #-1 means no spaces in the first width
characters
(line, text) = (line[:spc], line[spc:] + text)
else:
line = text
text = None
else:
line = text
text = None
if mode == RIGHTJUST:
line = line.rjust(width)
elif mode == CENTERED:
line = line.center(width)
else:
line = line.ljust(width)
output.append(line)
return "".join(output)

def emulateDisplay(text, width=24):
while text:
(line, text) = (text[:width], text[width:])
print line
print

if __name__ == "__main__":
message = """This is a long and rambling bit of nonsense,
four stone and 10 is a candidate for Top Model.

American Idol\tis a pastime of the American Idle
"""

emulateDisplay(fillWrap(message))
emulateDisplay(fillWrap(message, mode=CENTERED))
emulateDisplay(fillWrap(message, mode=RIGHTJUST, width=30),
width=30)
emulateDisplay(fillWrap(message, width=30), width=30)

============= (used fixed pitch to view)
C:\Documents and Settings\Dennis Lee Bieber>python "e:\UserData\Dennis
Lee Bieber\My Documents\E
udora\Script13.py"
This is a long and
rambling bit of
nonsense, four stone
and 10 is a candidate
for Top Model.
American Idol is a
pastime of the
American Idle

This is a long and
rambling bit of
nonsense, four stone
and 10 is a candidate
for Top Model.
American Idol is a
pastime of the
American Idle

This is a long and rambling
bit of nonsense, four stone
and 10 is a candidate for
Top Model. American Idol is
a pastime of the American
Idle

This is a long and rambling
bit of nonsense, four stone
and 10 is a candidate for
Top Model. American Idol is
a pastime of the American
Idle


C:\Documents and Settings\Dennis Lee Bieber>

--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top