0

我正在编写一个将每行限制为一定长度的程序。

这是我到目前为止得到的,我几乎完成了,但我仍然需要剪掉每一行,但我无法弄清楚。

def main():
    filename = input("Please enter the name of the file to be used: ")
    openFile = open(filename, 'r+')
    file = openFile.read()
    lLength = int(input("enter a number between 10 & 20: "))

    while (lLength < 10) or (lLength > 20) :
        print("Invalid input, please try again...")
        lLength = int(input("enter a number between 10 & 20: "))

    wr = textwrap.TextWrapper()
    wraped = wr.wrap(file)

    print("Here is your output formated to a max of", lLength, "characters per line: ")

    wr.width = lLength
    wr.expand_tabs = True
    for lines in wraped:
        print(lines)

编辑:

def main():
    filename = input("Please enter the name of the file to be used: ")
    openFile = open(filename, 'r')
    file = openFile.read()
    lLength = int(input("enter a number between 10 & 20: "))

    while (lLength < 10) or (lLength > 20) :
        print("Invalid input, please try again...")
        lLength = int(input("enter a number between 10 & 20: "))
    if (lLength > 10) or (lLength < 20):
        print("\nYour file contains the following text: \n" + file)
#=========================================================================
        wr = textwrap.TextWrapper(width=lLength)
        wraped = wr.wrap(file)

        print("\n\nHere is your output formated to a max of", lLength, "characters per line: ")

        for lines in wraped:
            print(lines)

main()

输出应该是这样的一个例子。如果指定的文件包含此文本:

hgytuinghdt #here the length is 11
ughtnjuiknshfyth #here the length is 16
nmjhkaiolgytuhngjuin #here the length is 20

并且 lLength 被指定为 15 那么这应该打印出来:

hgytuinghdt
ughtnjuiknshfyt
h
nmjhkaiolgytuhng
juin
4

3 回答 3

3

wr = textwrap.TextWrapper()应该是wr = textwrap.TextWrapper(width=length, expand_tabs=True) 然后你应该删除wr.width = lLengthand wr.expand_tabs = True。它们应该在wr.wrap()被调用之前运行,但是由于可以使用TextWrapper构造函数中的关键字参数来设置它,如最顶部所示,它们可以被删除。

PS:如果for lines in wraped: print(lines)用的话可以换成。print(wraped)TextWrapper.fill

于 2013-11-12T03:56:39.763 回答
0

尝试这个:

line = 'nmjhkaiolgytuhngjuin'
n = 5 # set the width here
a = [line[i:i+n] for i in range(0, len(line), n)]
print ("\n".join(a))
于 2013-11-12T04:09:12.003 回答
0

这可能会帮助您:

def wrap(f,n):
        fi=open(f,"w+")
        rl=fi.readlines()    
        for i in range(0,len(rl)):
            if len(rl[i]) > n:
                fi.write(rl[i][:n] +"\n" + rl[i][n:])
                fi.Close()
            else:
                fi.write(rl[i])
                fi.close()
于 2016-03-31T20:12:30.403 回答