文件中查找长度大于 80 个字符的文本行. 从最接近 80 个字符的单词断行, 把剩余文件插入到
下一行处.
程序执行完毕后, 应该没有超过 80 个字符的文本行了.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
filename = raw_input("input you filename: ")
lisr =[line.rstrip() for line in open(filename)]
result = []
index = 0
while index < len(lisr):
if len(lisr[index]) <= 80:
result.append(lisr[index]) #add the string's length less than 80
index = index + 1
#if the string's len large 80
else:
temp = lisr[index] #return a string,列表的下标索引值为字符串
pos = 79
while temp[pos] != ' ' and temp:
pos -= 1
result.append(temp[:pos])#将字符串添加到列表中
index = index + 1
if index < len(lisr):
lisr[index] = temp[pos:] + lisr[index]
else:
lisr.append(temp[pos:])
#print lisr[index]
filename1 = open("file1.txt",'w')
filename1.write('\n'.join(result))