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