Skip to content Skip to sidebar Skip to footer

In Text File, How Can I Parse Multilines In Particular Pattern Using Python?

I've asked a similar question in the past, but I'm not good at it, so I'll ask you again. Here is sample textfile.txt dummy01234567890 0987654321dummy -------start----

Solution 1:

Finite-state machine is adaptive and simple enough for most needs.

state = 'init'
arrays = []
with open('textfile.txt') as f:
    lines = []
    for line in f.readlines():
        ifstate == 'init':  # seek for start
             word = line.strip().strip('-')
             if word != 'start':
                 continuestate = 'start'
             lines = []
        elif state == 'start':  # start parsing now
             word = line.strip().strip('-')
             if word != 'end':
                 lines.append(line.strip())
                 continue# end current parsing now
             arrays.append('\n'.join(lines))
             state = 'init'

Solution 2:

You can do something like this to achieve the desired result :

text = """dummy01234567890
    0987654321dummy 
    -------start-------(It is possible to modify)
    text line1
    text line2
    -------end---------(It is possible to modify)
    12345678910
    qwertyuiop        
    -------start-------(It is possible to modify)
    text line3
    text line4
    -------end---------(It is possible to modify)
    ;p12309809128309123
    dummyline1235567"""

text_list = text.splitlines()
print(['\n'.join([text_list[3+i*6].strip(), text_list[4+i*6].strip()]) for i in xrange(len(text_list)/6)])

This will result in :

['text line1\ntext line2', 'text line3\ntext line4']

Post a Comment for "In Text File, How Can I Parse Multilines In Particular Pattern Using Python?"