Trying to justify text using Python

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • growthndevlpmnt
    New Member
    • May 2012
    • 5

    Trying to justify text using Python

    Ok so I'm supposed to be taking a input text file and justifying it. I've have gotten the text to do character justification bar the last line. I'm trying to figure out how to iterate over each space and insert a ' ' to get the last last up to the specified length.

    If I try
    Code:
    for ' ' in new:
        insert(new,' ',find(' '))
    in the spirit of simple style that python has taught me,
    I get a non iterable error. Hence the while loop.

    Also is there a way to get this bad-boy to justified by words and not chars?

    I was using the 'Lorem ipsum...' paragraph as my default text.

    Any help is appreciated.


    Code:
    inf = open('file_in.txt', 'r')
    of = open('file_jus.txt', 'w')
    
    inf.tell()
    
    n = input('enter the number of characters per line: ')
    
    def insert(original, new, pos):
      #Inserts new inside original at pos.
      return original[:pos] + new + original[pos:] 
    
    try:
        print 'you entered {}\n'.format(int(n))
    except:
        print 'there was an error'
        n = input('enter the number of characters per line: ')
    else:
        new = inf.readline(n)
        def printn(l):
            
            print>>of, l+'\n'
            print 'printing to file',
            print '(first char: {} || last char: {})'.format(l[0],l[-1])
    
        while new != '': #multiple spaces present at EOF
            if new[0] != ' ': #check space at beginning of line
                if new[-1] != ' ': # check space at end of line
                    while (len(new) < n):
                        new = insert(new,' ',(new.find(' ')))
                    printn(new)
                
            elif new[0] == ' ':
                new = new.lstrip() #remove leading whitespace
                new = insert(new,' ',(new.find(' ')))
                while (len(new) < n):
                    new = insert(new,' ',(new.find(' ')))
                printn(new)
                
            elif new[-1] == ' ':
                new = new.rstrip() #remove trailing whitespace
                new = insert(new, ' ',(new.rfind(' ')))
                while (len(new) < n):
                    new = insert(new,' ',(new.rfind(' ')))
                printn(new)       
                
            new = inf.readline(n)
            
    
        print '\nclosing files...'
        inf.close()
        print 'input closed'
        of.close()
        print 'output closed'
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    Code:
    new = inf.readline(n)
    I think you want inf.read(n) here instead. Print the var "new" and it's length after the read to be sure that the program is doing what you think it is. Post back if there are further problems as I would read the entire file and split before the word that exceeds the length, and then add spaces and a newline. In addition, instead of testing the first and last character for a space, you can strip() the record and avoid all of the if/elif statements. Note also that "new" is already used by python so you should choose another variable name.

    I will leave it up to you to add the correct number of spaces to each element of the list to right justify.
    Code:
    ## simulate read the entire file and add some additional punctuation
    s="The quick brown fox, jumped over\n the lazy dogs."
    s_list = s.split()
    split_len=18
    
    list_of_records=[]
    ctr=0
    next_record=""
    for word in s_list:
        if len(next_record) + len(word) < split_len-1:
            if len(next_record):  ## no space at the beginning
                next_record += " "
            next_record += word
        else:     ## limit reached=start next record
            list_of_records.append(next_record)
            next_record=word
    
    if len(next_record):
        list_of_records.append(next_record)
    
    print "\n".join(list_of_records)

    Comment

    • dwblas
      Recognized Expert Contributor
      • May 2008
      • 626

      #3
      For completeness, this code reads the entire file and splits it into records stored in a list based on a moving start and end position. Once again you will have to iterate over the list and add appropriate spaces to right justify.
      Code:
      ## simulate read the entire file and add some additional punctuation
      s="The quick brown fox, jumped over\n some of the lazy dogs and cats and elephants."
      s=s.replace("\n", "")
      last_position=len(s)-1
      
      split_len=18
      list_of_records=[]
      start=0
      
      while True:
          end=start+split_len+1 # +1=allow for space=next character
          rec=s[start:end].strip()
          ctr = -1       
          if end < last_position:
              ## look for space from right to left
              while rec[ctr] != " ":     ## assumes space, or more than one word here
                  ctr -= 1
      
              list_of_records.append(rec[:ctr].strip())
              start += len(rec[:ctr])+1     ## +1 = skip space
          else:   ## end of file reached
              list_of_records.append(s[start:].strip())
              break
      
      print "\n".join(list_of_records)

      Comment

      • growthndevlpmnt
        New Member
        • May 2012
        • 5

        #4
        Thanks a lot. You have helped me drastically improve readability of my code. I'm still working out the method you suggested, but i already like the way it looks.

        Comment

        Working...