代码之家  ›  专栏  ›  技术社区  ›  ontherocks

Python:提取特定行之间的行

  •  0
  • ontherocks  · 技术社区  · 7 年前

    Windows 7 64位上的Python 3.6.7 64位

    后面的名字 # 是容器名称,它们包含以开头的对象 '-'

    #abc contains:
    date 20-Oct
    - mmm
    - nnn
    - ooo
    #def contains:
    date 23-Oct
    - ppp
    #ghi contains:
    date 24-Oct
    - sss
    - ttt
    #jkl contains:
    date 26-Oct
    - uuu
    - vvv
    - www
    

    目标是只打印以下行(即容器的内容)

    mmm, nnn, ooo @abc
    ppp @def
    sss, ttt @ghi
    uuu, vvv, www @jkl
    

    import re
    
    with open('mydata.txt', 'r') as infile:
        container = ''
        allcontents = ''
        for line in infile:
            line = line.strip()
            if line.endswith('contains:'):
                print(allcontents[:-2] + container)
                container = re.search('#(.+)\scontains', line).group(1)
                container = '@' + container
                allcontents = '' #reset allcontents
    
            if line.startswith('- '):
                content = re.search('-\s(.+)$', line).group(1)
                allcontents = allcontents + content + ', '
    

    mmm, nnn, ooo@abc
    ppp@def
    sss, ttt@ghi
    

    我该如何解决这个问题?

    2 回复  |  直到 7 年前
        1
  •  2
  •   edilio    7 年前

    正如@Austin所说,你需要在循环之外打印。以下是提供所需输出的修改:

    import re
    
    with open('mydata.txt', 'r') as infile:
        container = ''
        allcontents = ''
        for line in infile:
            line = line.strip()
            if line.endswith('contains:'):
                print(allcontents[:-2] + container)
                container = re.search('#(.+)\scontains', line).group(1)
                container = '@' + container
                allcontents = ''  # reset allcontents
    
            if line.startswith('- '):
                content = re.search('-\s(.+)$', line).group(1)
                allcontents = allcontents + content + ', '
        if container:
            print(allcontents[:-2] + container)
    
        2
  •  2
  •   Austin    7 年前

    print(allcontents[:-2] + container)
    

    您的最后一行已存储在中 allcontents ,只是你没有打印出来。