【问题标题】:End up loop once the next document starts (Python 3)下一个文档开始后结束循环(Python 3)
【发布时间】:2019-05-12 05:21:24
【问题描述】:

我想在下一个条目开始后结束一个循环。例如,假设我有以下由三个文档组成的 txt 文件:

Document 1
text1
text1
tex1
Document 2
text2
text2
text2    
Document 3
text3
text3
text3

我正在尝试构建一个JSON 文件,该文件将单个文章中的每个文本连接起来。例如'body' = text1 text1 text1'body' = text2 text2 text2;和'body' = text2 text2 text2。为此,我搜索单词Document,然后基本上将其后面的文本连接成一行。问题是我的代码跳过了一个文档,所以它只适用于文档 1 和 3:

for line in f:
    if re.search(r"Document ", line):
        text = ''
        while not re.search(r"Document ", line):
            text += line+' '                     
        article['body'] = text

知道如何在下一个文档开始后告诉代码停止 (while not) 吗?

【问题讨论】:

    标签: json regex python-3.x loops


    【解决方案1】:

    您可以使用以下 Python 代码:

    article = []
    start_matching = False
    text = ""
    with open(path, "r") as file:
        for line in file:
            if re.match(r"Document\s+\d", line):
                start_matching = True
                if text:
                    article.append(text.strip())
                    text = ""
                text += line
            else:
                if start_matching:
                    text += line
    if text:
        article.append(text.strip())
    
    print(article)
    # => ['Document 1\ntext1\ntext1\ntex1', 'Document 2\ntext2\ntext2\ntext2', 'Document 3\ntext3\ntext3\ntext3']
    

    请参阅online demo

    关键是匹配只在一行以Document、1+ 个空格和一个数字 (if re.match(r"Document\s+\d", line):) 开头时开始,然后添加属于该文档的行,然后附加到列表中(您可以调整输出满足您的需求)。

    【讨论】:

      【解决方案2】:

      如果我们使用正则表达式并且我们可以在正则表达式中完成所有操作,那么让正则表达式完成艰苦的工作:

      >>> regex = r"Document\s+\d+((?:(?!\s*Document\s+\d+)\s*.*)+)"
      >>> re.findall(regex, str)
      

      输出

      ['text1\ntext1\ntex1', 'text2\ntext2\ntext2', 'text3\ntext3\ntext3']
      

      live demo here

      正则表达式分解:

      • Document\s+\d+ 匹配分隔符字符串
      • ( 捕获组 #1 的开始
        • (?:非捕获组开始
          • (?!\s*Document\s+\d+) 如果我们没有到达下一个分隔符
          • \s*.*匹配当前行
        • )+非捕获组结束,尽可能重复
      • ) 捕获组 #1 结束

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-30
        • 1970-01-01
        • 2012-05-14
        • 2022-08-14
        • 2016-06-06
        • 1970-01-01
        • 1970-01-01
        • 2015-11-28
        相关资源
        最近更新 更多