그래, 입력 텍스트 파일을 가져 와서 마이크로 소프트 워드 나 다른 워드 프로세서처럼 정당화하려고한다. 필자는 마지막 줄에서 문자 정렬 막대를 처리하는 텍스트를 얻었습니다. 마지막 줄의 각 공백을 반복하는 방법을 알아 내려고 ' '
을 삽입하여 지정된 길이까지 마지막 마지막을 가져옵니다.일련의 공백을 반복하는 방법은 무엇입니까?
내가하려고하면 :
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 .
예를 들어 입/출력 할 수 있습니까? – robert
예제 입력/출력이 추가되었습니다. – growthndevlpmnt