文本结束时停止while循环

时间:2019-03-22 15:08:11

标签: python string while-loop

我有一个程序可以遍历一本书的各个行,以匹配我创建的一些标签,这些标签指示本书各章的开始和结束。我想将每个章节分成一个不同的文件。程序会找到每个章节,并要求用户命名文件,然后继续进行到下一章,依此类推。我不知道确切地把“中断”放在哪里,或者不知道什么可以阻止我的循环。该程序运行良好,但是到达最后一章时,它会回到第一章。我想停止循环并在标记和章节完成时终止程序,并打印类似“章节末尾”的内容。有人可以帮我吗?代码如下:

import re
def separate_files ():
    with open('sample.txt') as file:
        chapters = file.readlines()



pat=re.compile(r"[@introS\].[\@introEnd@]")
reg= list(filter(pat.match, chapters))
txt=' '

while True:
    for i in chapters:
        if i in reg:
            print(i)
            inp=input("write text a file? Y|N: ")
            if inp =='Y':
                txt=i
                file_name=input('Name your file: ')
                out_file=open(file_name,'w')
                out_file.write(txt)
                out_file.close()
                print('text', inp, 'written to a file')
            elif inp =='N':
                break
        else:
            continue
    else:
        continue


separate_files()

2 个答案:

答案 0 :(得分:2)

我认为更简单的定义是

import re
def separate_files ():
    pat = re.compile(r"[@introS\].[\@introEnd@]")

    with open('sample.txt') as file:

        for i in filter(pat.match, file):
            print(i)
            inp = input("write text to a file? Y|N: ")
            if inp != "Y":
                continue

            file_name = input("Name of your file: ")
            with open(file_name, "w") as out_file:
                out_file.write(i)
            print("text {} written to a file".format(i))

在每种情况下,都应尽快继续循环,这样就不必将下面的代码嵌套得越来越深。同样,也没有必要一次将整个文件读入内存。只需将每行与出现的图案匹配即可。

您还可以考虑简单地询问文件名,将空白文件名视为拒绝将行写入文件。

for i in filter(pat.match, file):
    print(i)
    file_name = input("Enter a file name to write to (or leave blank to continue: ")
    if not file_name:
        continue

    with open(file_name, "w") as out_file:
        out_file.write(i)
    print("text {} written to {}".format(i, file_name)

答案 1 :(得分:0)

我无法运行您的代码,但是我认为如果您删除

while True:

行它应该工作正常。这将始终执行,因为没有检查任何内容

相关问题