好吧,所以我正在嘗試輸入文本文件並將其證明爲微軟文字或任何其他文字處理程序。我已經得到文字做字符理由吧最後一行。我試圖找出如何迭代最後一行中的每個空格,並插入' '
以使最後一個最後達到指定的長度。如何遍歷一系列空格?
如果我嘗試:
for ' ' in new:
insert(new,' ',find(' '))
在簡約風格的精神,Python有教我,我 得到非迭代的錯誤。因此,在代碼循環中。但是這隻會在第一個空格中插入所有的空格。
還有沒有辦法讓這個程序通過單詞而不是字符來證明?
我正在使用'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