在文本文件中,如何使用python解析特定模式中的多行?

2024-04-27 00:36:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我以前也问过类似的问题,但我不擅长,所以我再问你一次。你知道吗

这是样品文本文件.txt你知道吗

    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

我想分析一下

“文本行1\n文本行2”→数组[0]

“文本行3\n文本行4”→数组[1]

我应该如何用python编写源代码?你知道吗

我应该使用拆分函数两次吗?你知道吗


Tags: totext文本txtis样品it数组
2条回答

您可以这样做以获得所需的结果:

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

这将导致:

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

Finite-state machine是自适应的,对于大多数需求来说足够简单。你知道吗

state = 'init'
arrays = []
with open('textfile.txt') as f:
    lines = []
    for line in f.readlines():
        if state == 'init':  # seek for start
             word = line.strip().strip('-')
             if word != 'start':
                 continue
             state = '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'

相关问题 更多 >