By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,760 Members | 1,098 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,760 IT Pros & Developers. It's quick & easy.

Trying to justify text using Python

P: 5
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
Expand|Select|Wrap|Line Numbers
  1. for ' ' in new:
  2.     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.


Expand|Select|Wrap|Line Numbers
  1. inf = open('file_in.txt', 'r')
  2. of = open('file_jus.txt', 'w')
  3.  
  4. inf.tell()
  5.  
  6. n = input('enter the number of characters per line: ')
  7.  
  8. def insert(original, new, pos):
  9.   #Inserts new inside original at pos.
  10.   return original[:pos] + new + original[pos:] 
  11.  
  12. try:
  13.     print 'you entered {}\n'.format(int(n))
  14. except:
  15.     print 'there was an error'
  16.     n = input('enter the number of characters per line: ')
  17. else:
  18.     new = inf.readline(n)
  19.     def printn(l):
  20.  
  21.         print>>of, l+'\n'
  22.         print 'printing to file',
  23.         print '(first char: {} || last char: {})'.format(l[0],l[-1])
  24.  
  25.     while new != '': #multiple spaces present at EOF
  26.         if new[0] != ' ': #check space at beginning of line
  27.             if new[-1] != ' ': # check space at end of line
  28.                 while (len(new) < n):
  29.                     new = insert(new,' ',(new.find(' ')))
  30.                 printn(new)
  31.  
  32.         elif new[0] == ' ':
  33.             new = new.lstrip() #remove leading whitespace
  34.             new = insert(new,' ',(new.find(' ')))
  35.             while (len(new) < n):
  36.                 new = insert(new,' ',(new.find(' ')))
  37.             printn(new)
  38.  
  39.         elif new[-1] == ' ':
  40.             new = new.rstrip() #remove trailing whitespace
  41.             new = insert(new, ' ',(new.rfind(' ')))
  42.             while (len(new) < n):
  43.                 new = insert(new,' ',(new.rfind(' ')))
  44.             printn(new)       
  45.  
  46.         new = inf.readline(n)
  47.  
  48.  
  49.     print '\nclosing files...'
  50.     inf.close()
  51.     print 'input closed'
  52.     of.close()
  53.     print 'output closed'
  54.  
  55.  
May 15 '12 #1
Share this Question
Share on Google+
3 Replies

Expert 100+
P: 626
Expand|Select|Wrap|Line Numbers
  1. 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.
Expand|Select|Wrap|Line Numbers
  1. ## simulate read the entire file and add some additional punctuation
  2. s="The quick brown fox, jumped over\n the lazy dogs."
  3. s_list = s.split()
  4. split_len=18
  5.  
  6. list_of_records=[]
  7. ctr=0
  8. next_record=""
  9. for word in s_list:
  10.     if len(next_record) + len(word) < split_len-1:
  11.         if len(next_record):  ## no space at the beginning
  12.             next_record += " "
  13.         next_record += word
  14.     else:     ## limit reached=start next record
  15.         list_of_records.append(next_record)
  16.         next_record=word
  17.  
  18. if len(next_record):
  19.     list_of_records.append(next_record)
  20.  
  21. print "\n".join(list_of_records) 
May 15 '12 #2

Expert 100+
P: 626
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.
Expand|Select|Wrap|Line Numbers
  1. ## simulate read the entire file and add some additional punctuation
  2. s="The quick brown fox, jumped over\n some of the lazy dogs and cats and elephants."
  3. s=s.replace("\n", "")
  4. last_position=len(s)-1
  5.  
  6. split_len=18
  7. list_of_records=[]
  8. start=0
  9.  
  10. while True:
  11.     end=start+split_len+1 # +1=allow for space=next character
  12.     rec=s[start:end].strip()
  13.     ctr = -1       
  14.     if end < last_position:
  15.         ## look for space from right to left
  16.         while rec[ctr] != " ":     ## assumes space, or more than one word here
  17.             ctr -= 1
  18.  
  19.         list_of_records.append(rec[:ctr].strip())
  20.         start += len(rec[:ctr])+1     ## +1 = skip space
  21.     else:   ## end of file reached
  22.         list_of_records.append(s[start:].strip())
  23.         break
  24.  
  25. print "\n".join(list_of_records) 
May 15 '12 #3

P: 5
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.
May 15 '12 #4

Post your reply

Sign in to post your reply or Sign up for a free account.