【问题标题】:stop while loop when the text ends文本结束时停止 while 循环
【发布时间】:2019-08-13 14:47:12
【问题描述】:

我有一个程序,它循环遍历一本书的行来匹配我创建的一些标签,这些标签指示了本书每一章的开始和结束。我想将每一章分成不同的文件。程序找到每一章并要求用户为文件命名,然后继续直到下一章,依此类推。我不知道在哪里放置我的“休息”或可以阻止我的循环的东西。该程序运行良好,但是当它到达最后一章时,它又回到了第一章。我想在标签和章节完成时停止循环并终止程序,并打印诸如“章节结束”之类的内容。任何人都可以帮助我吗?代码如下:

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

【问题讨论】:

  • “但是当它到达最后一章时,它会回到第一章”......是的。因为for i in chapters: 循环结束并且外部while 重复所有内容。只需删除 while(当你在它的时候,还有最后的 else: continue,我 200% 确定它放错了)
  • 除非您自己破坏它,否则使用“While True”将永远不会结束,我建议您找到一个实际的真/假条件检查以与您的 while 语句一起使用,以便当该条件为假时循环结束。或者您可以删除 while,因为您已经使用“for i in chapters”语句循环数据。
  • while 循环是否应该在 separate_files 内? (似乎是这样,否则 chapters 没有定义。)
  • @GPhilo,好的!我将尝试删除 while True。
  • 这不是您在代码中遇到的唯一错误,但您可以从那里开始。正如 chepner 指出的那样,chapters 没有在任何地方定义

标签: python string while-loop


【解决方案1】:

我认为更简单的定义是

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)

【讨论】:

  • 非常感谢!我想知道是否可以要求程序创建文件并自动为每个文件命名,而不是要求用户命名文件来创建它。那可能吗?如果是这样,你能告诉我怎么做吗?
【解决方案2】:

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

while True:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2014-04-20
    • 1970-01-01
    • 2016-11-02
    • 2013-09-28
    • 1970-01-01
    • 2012-12-23
    相关资源
    最近更新 更多