0

こんにちは皆さん、私はこの問題に問題があります。問題は、ファイル内のすべての行の後にカウントをリセットする必要があることです。カウントをリセットしたい場所がわかるようにコメントを付けました。

プログラムは、指定された lineLength ごとに各行をカットすることを想定しています。

def insert_newlines(string, afterEvery_char):
    lines = []
    for i in range(0, len(string), afterEvery_char):
        lines.append(string[i:i+afterEvery_char])
        string[:afterEvery_char] #i want to reset here to the beginning of every line to start count over
    print('\n'.join(lines))

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

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

    print("\nYour file contains the following text: \n" + file + "\n\n") # Prints original File to screen
    print("Here is your output formated to a max of", lineLength, "characters per line: ")

    insert_newlines(file, lineLength)
main()

元。ファイルにこのような 3 行があり、各行が 20 文字の場合

andhsytghfydhtbcndhg 
andhsytghfydhtbcndhg
andhsytghfydhtbcndhg

線がカットされた後、次のようになります

andhsytghfydhtb
cndhg
andhsytghfydhtb
cndhg
andhsytghfydhtb
cndhg

ファイル内のすべての行の後にカウントをリセットしたい。

4

2 に答える 2

1

私はあなたの問題を理解しているかどうかわかりませんが、あなたのコメントから、入力文字列 (ファイル) を lineLength の長さの行に切り取りたいだけのようです。これは、insert_newlines() で既に行われているため、コメント付きの行は必要ありません。

ただし、改行文字で終わる文字列を意味する行を出力したい場合は、次のようにファイルを単純に読み取ることができます。

lines = []
while True:
    line = openFile.readline(lineLength)
    if not line:
        break
    if line[-1] != '\n':
        line += '\n'
    lines.append(line)
print(''.join(lines))

または代わりに:

lines = []
while True:
    line = openFile.readline(lineLength)
    if not line:
        break
    lines.append(line.rstrip('\n'))
print('\n'.join(lines))
于 2013-11-12T19:05:31.503 に答える
0

ここで問題がわかりません。コードは問題なく動作するようです:

def insert_newlines(string, afterEvery_char):
    lines = []
    # if len(string) is 100 and afterEvery_char is 10
    # then i will be equal to 0, 10, 20, ... 90
    # in lines we'll have [string[0:10], ..., string[90:100]] (ie the entire string)
    for i in range(0, len(string), afterEvery_char):
        lines.append(string[i:i+afterEvery_char])
        # resetting i here won't have any effect whatsoever
    print('\n'.join(lines))


>>> insert_newlines('Beautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\n..', 10)
Beautiful
is better
than ugly.

Explicit
is better
than impli
cit.
Simpl
e is bette
r than com
plex.
..

それはあなたが望むものではありませんか?

于 2013-11-12T18:49:00.317 に答える