python随笔(一)

文本处理. 人们输入的文字常常超过屏幕的最大宽度. 编写一个程序, 在一个文本
文件中查找长度大于 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))

        




    



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值