文本结束时循环时停止



我有一个程序,该程序循环遍历一本书的行,以匹配我创建的一些标签,以指示本书的每一章的开始和结尾。我想将每个章节分为不同的文件。该程序找到每章,并要求用户命名文件,然后继续进行直到下一章等。我不知道将"休息"或可以阻止我的循环的东西确切地放在哪里。该程序运行良好,但是当它到达最后一章时,它可以追溯到第一章。我想停止循环并在标签和章节完成时终止程序,并打印诸如"章节的结尾"之类的内容。谁能帮我吗?代码如下:

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

我认为更简单的定义是

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)

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

while True:

行应该很好。这将始终执行,因为没有任何检查

最新更新