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() 中完成了,不需要有注释的行。

但是,如果要输出行,表示以换行符结尾且长度不应超过 lineLength 的字符串,则可以像这样简单地读取文件:

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 回答