Python textwrap和每行后重置计数

时间:2013-11-12 18:18:23

标签: python python-3.x computer-science

大家好,我有这个问题的问题,问题是我需要在文件中的每一行后重置计数,我发表评论,以便你可以看到我想重置计数的位置。

程序假设在每个指定的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

我想在文件中的每一行之后重置计数。

2 个答案:

答案 0 :(得分:1)

我不确定我理解你的问题,但是根据你的评论,你似乎只想将输入字符串(文件)剪切为lineLength long。这已经在你的insert_newlines()中完成了,不需要那里有注释的行。

但是,如果你想输出的行意味着以newline char结尾的字符串不应该超过lineLength long,那么你可以简单地读取这样的文件:

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))

答案 1 :(得分: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.
..

不是你想要的吗?