473,387 Members | 1,799 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

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
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
3 6080
dwblas
626 Expert 512MB
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
dwblas
626 Expert 512MB
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
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

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

Similar topics

0
by: Just Me | last post by:
I have a RichTextBox app that I converted from using the riched20.dll before ..net. The old app used to be able to justify text. I still call the windows API to set alignment to Justify but...
12
by: nuttydevil | last post by:
Hey everyone! I'm hoping someone will be able to help me, cause I haven't had success searching on the web so far... I have large chunks of text ( all in a long string) that are currently all in...
0
by: Doug Caldwell | last post by:
Hi! ** Accessing the USGS Web Service Using Python ** I am trying to access the US Geological Survey's gazetteer SOAP web service using Python to find the locations of all the places with the...
0
by: Duracel | last post by:
I'm using DrawString and the Format object (StringFormat) to justify text left and right, with word wrap. It's working nicely. Is there any way to get text that is just plain justified, in the...
2
by: RobinS | last post by:
Is it possible to left-justify, center, or right-justify text on a panel when drawing it using DrawString? I looked at the StringAlignment class, but all it has is far, near, and center. ...
9
by: dominiquevalentine | last post by:
Hello, I'm a teen trying to do my part in improving the world, and me and my pal came up with some concepts to improve the transportation system. I have googled up and down for examples of using...
2
by: Krishna | last post by:
I was trying to delete rows in an existing .xls file using python. How do I do that? I was using the following code, it seem to work if I type in python window, but if I save it in text editor and...
2
by: lee.walczak | last post by:
Hi, I am using Tkinter & the Kevin Walzer's TableList Wrapper for python implemented GUI: http://tkinter.unpythonic.net/wiki/TableListWrapper The TableList has been extremely useful in...
3
by: yuleball | last post by:
I want to fully justify text in rtb. I am designing an urdu editor. The urdu language is written from right to left. So the text is right justified initially. Waiting for reply
6
by: ammar yasir | last post by:
how to justify text in memo field of a form and a report? i need some sort of code that keeps the text in memo field justified. there are only 3 options of text align, right,left, distributed. i want...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.