text wrapping help

Discussion in 'Python' started by Ryan K, Mar 1, 2007.

  1. Ryan K

    Ryan K Guest

    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
    Ryan K, Mar 1, 2007
    #1
    1. Advertising

  2. Ryan K

    Ryan K Guest

    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.


    On Feb 28, 7:06 pm, "Ryan K" <> wrote:
    > 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
    Ryan K, Mar 1, 2007
    #2
    1. Advertising

  3. Ryan K

    Guest

    On Feb 28, 4:06 pm, "Ryan K" <> wrote:
    > 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)


    --
    Hope this helps,
    Steven
    , Mar 1, 2007
    #3
  4. Ryan K

    Ryan K Guest

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



    On Feb 28, 8:27 pm, wrote:
    > On Feb 28, 4:06 pm, "Ryan K" <> wrote:
    >
    > > 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)
    >
    > --
    > Hope this helps,
    > Steven
    Ryan K, Mar 1, 2007
    #4
  5. Ryan K

    Guest

    On Feb 28, 5:50 pm, "Ryan K" <> wrote:

    > On Feb 28, 8:27 pm, wrote:
    >
    > > 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)

    >
    > > --
    > > Hope this helps,
    > > Steven

    >
    > 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)

    --
    Hope this helps,
    Steven
    , Mar 1, 2007
    #5
  6. Ryan K wrote:

    > 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

    --
    BOFH excuse #325:

    Your processor does not develop enough heat.
    Bjoern Schliessmann, Mar 1, 2007
    #6
  7. 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

    HTTP://wlfraed.home.netcom.com/
    (Bestiaria Support Staff: )
    HTTP://www.bestiaria.com/
    Dennis Lee Bieber, Mar 1, 2007
    #7
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Mike Casey
    Replies:
    7
    Views:
    3,939
    Scott M.
    Dec 19, 2003
  2. PeteZ

    AdRotator and Text Wrapping

    PeteZ, Dec 30, 2004, in forum: ASP .Net
    Replies:
    0
    Views:
    393
    PeteZ
    Dec 30, 2004
  3. Dan
    Replies:
    0
    Views:
    460
  4. Replies:
    5
    Views:
    8,865
    Jukka K. Korpela
    Mar 7, 2006
  5. Coby Herd

    Help wrapping text around an image

    Coby Herd, Jan 26, 2006, in forum: ASP General
    Replies:
    3
    Views:
    219
    Roland Hall
    Jan 27, 2006
Loading...

Share This Page