Python解析选定的文本文件区域/范围

时间:2014-07-11 18:27:17

标签: python parsing

我想打印文本文件text.txt的选定部分,其中包含:

tickme 1.1(no.3)
lesson1-bases
lesson2-advancedfurther
para:using the dsp signals are sened via a transmitter to conver to analong signals and gets the output in the form of digital signal

tickme 2.2(no.4)
lesson1-basics2
lesson2-advanced4
para:using the DIGITAL signals are sened via a transmitter to conver to analong signals and gets the output in the form of digital signal

tickme 3.3(no.5)
lesson1-bas
lesson2-adv
para:using the dsp signals are sened via a transmitter to conver to analong signals and gets the output in the form of digital signal

这里有3个勾选我,但我想选择一个特定的tickme 2.2(no.4),我必须在开始tickme 3.3(no.5)之前解析文本。

因此,如果段落中有“DIGITAL”,则必须打印“lesson1”,因为它会引起歧义我想选择文本文件的范围。

输出:

lesson1-basics2

由于它有一个共同的第1课,所以勾选我,我需要选择特定区域来解析tickme2.2(no.4)到tickme 3.3(no.5)有没有办法得到一个特定区域的范围并进行解析?并且可能会有大量的数据与实例相同。

问题:它没有选择特定范围。

searchstring = ""
with open('text.txt','r') as file:

    for line in file:
        if 'tickme' in line:
            searchstring = line
        if searchstring != '':
            if 'DIGITAL' in line:
                print(searchstring)
                print(line)

1 个答案:

答案 0 :(得分:1)

将文件拆分为如下批次:

以open('txt.txt')为f:     批次= []

t = []
for l in line:
    if 'tickme' in l:
        # Start a new bactch after saving the previous batch 
        if t: batches.apend(t)
        t = [l.strip()]
    else:
        if len(l.strip()) > 1: t.append(l.strip())