2012-05-15 3 views
0

그래, 입력 텍스트 파일을 가져 와서 마이크로 소프트 워드 나 다른 워드 프로세서처럼 정당화하려고한다. 필자는 마지막 줄에서 문자 정렬 막대를 처리하는 텍스트를 얻었습니다. 마지막 줄의 각 공백을 반복하는 방법을 알아 내려고 ' '을 삽입하여 지정된 길이까지 마지막 마지막을 가져옵니다.일련의 공백을 반복하는 방법은 무엇입니까?

내가하려고하면 :

for ' ' in new: 
    insert(new,' ',find(' ')) 
파이썬 가르쳐 것을 심플한 스타일의 정신에

, '비 반복 가능한 오류가 발생합니다. 따라서 코드 루프에서 while. 그러나 이것은 첫 번째 공간에 모든 공백 만 삽입합니다.

또한이 프로그램을 문자가 아닌 단어로 정렬 할 수있는 방법이 있습니까?

내 기본 텍스트로 'Lorem ipsum ...'문단을 사용하고있었습니다.

도움을 주시면 감사하겠습니다.

전체 코드 :

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' 

입력 :

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. 

경우 광고의 길이 n == 37

출력 :

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         . 
+3

예를 들어 입/출력 할 수 있습니까? – robert

+0

예제 입력/출력이 추가되었습니다. – growthndevlpmnt

답변

1

나는 ... 당신이 원하는 것을 이해하는 약간의 문제가있어 당신이textwrap 모듈 (http://docs.python.org/library/textwrap.html)를 할 수 있습니다 것 같다. 이 원하지 않을 경우 ... 나를 알고 내가 행복이 답변 삭제됩니다하자

편집

이 당신이 원하는 일을합니까? 이 상황에서

EDIT2

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) 

, 나는 긴 각 N 블록입니다 문자열로 문자열을 깰 목록에 차례로 그 문자열을 저장 한 후 나는 것 "\ n을"것입니다. 하루가 끝나면 가입하십시오 (list_of_strings). 나는 이것이 숙제라고 생각하기 때문에 코드화하지 않을 것이다.

+0

그건 좋은 제안이지만, 나는 도서관 기능을 사용하지 않아야한다고 생각합니다. 왜, 나는 잘 모르겠다. 하지만 그것은 내 프로그램 사양에 있습니다. – growthndevlpmnt

+0

@growthndevlpmnt 숙제 인 경우이를 숙제로 지정해야합니다. – mgilson

+0

괜찮습니다. 학교가 끝났어. 이것은 나의 연구 멘토로부터의 난제로서의 도전입니다. 나는 그것이 숙제로 분류 될 수 있다고 생각한다. 그래도 도움을 주셔서 감사합니다. – growthndevlpmnt

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

당신은 리터럴에 할당하려고합니다. 이렇게 해보십시오.

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

+0

또는 '새 x in new : if x ==' ': insert (new, x, find (' ')) – mgilson

+0

오 예. 나는 대답을 편집 할 것이다. 감사! – VenkatH

+0

줄의 모든 문자를 반복하지 않습니까? 나는 그 공간 만 원해. – growthndevlpmnt

관련 문제