سؤال

Ok so I'm trying to take an input text file and justify it like microsoft word or any other word processor would. 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 in the last line and insert a ' ' to get the last last up to the specified length.

If I try:

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 in the code loop. But this only inserts all the spaces at the first space.

Also is there a way to get this program to justified by words and not chars?

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

Any help is appreciated.

full code:

inf = open('filein.txt', 'r')
of = open('fileout.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'

input:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

If line length n == 37

output:

Lorem ipsum dolor sit amet, consectet
ur adipisicing elit, sed do eiusmod t
magna aliqua. Ut enim ad minim veniam
, quis nostrud exercitation ullamco l
consequat. Duis aute irure dolor in r
cillum dolore eu fugiat nulla pariatu
non proident, sunt in culpa qui offic
ia deserunt mollit anim id est laboru
m                                   .
هل كانت مفيدة؟

المحلول

I'm having a little trouble understanding what you want to do ... It seems like you might want the textwrap module ( http://docs.python.org/library/textwrap.html ). If this isn't what you want, let me know and I'll happily delete this answer...

EDIT

Does this do what you want?

s="""Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute 
irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla 
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum."""

import textwrap

print textwrap.fill(s,37)

EDIT2

In this situation, I would break your string into substrings that are each N blocks long, store those strings in a list one after another and then I would "\n".join(list_of_strings) at the end of the day. I won't code it up though since I suspect this is homework.

نصائح أخرى

for ' ' in new:
    insert(new,' ',find(' '))

You're tyring to assign to a literal. Try it like this

for x in new:
    if x == ' ':
        insert(new, x, find(' '))

and see if it works?

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top