好的,所以我正在尝试获取输入文本文件并像 microsoft word 或任何其他文字处理器一样证明它的合理性。我已经得到文本来做字符对齐栏的最后一行。我试图弄清楚如何遍历最后一行中的每个空格并插入 a' '
以使最后一个最后一个达到指定的长度。
如果我尝试:
for ' ' in new:
insert(new,' ',find(' '))
本着 python 教给我的简单风格的精神,我得到了一个不可迭代的错误。因此代码循环中的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 .