Repeatedly extract a line between two delimiters in a text file, Python

后端 未结 4 707
情话喂你
情话喂你 2020-12-06 11:07

I have a text file in the following format:

DELIMITER1
extract me
extract me
extract me
DELIMITER2

I\'d like to extract every block of

4条回答
  •  醉酒成梦
    2020-12-06 11:25

    If the delimiters are within a line:

    def get_sentences(filename):
        with open(filename) as file_contents:
            d1, d2 = '.', ',' # just example delimiters
            for line in file_contents:
                i1, i2 = line.find(d1), line.find(d2)
                if -1 < i1 < i2:
                    yield line[i1+1:i2]
    
    
    sentences = list(get_sentences('path/to/my/file'))
    

    If they are on their own lines:

    def get_sentences(filename):
        with open(filename) as file_contents:
            d1, d2 = '.', ',' # just example delimiters
            results = []
            for line in file_contents:
                if d1 in line:
                    results = []
                elif d2 in line:
                    yield results
                else:
                    results.append(line)
    
    sentences = list(get_sentences('path/to/my/file'))
    

提交回复
热议问题