简体   繁体   中英

How to creat loops reading specific lines in python

I am trying a program with can output specifics lines in loops(starts with 1 type and ends befor the new one) :

the text is like:

<<0>>type : Installed<<1>>nom : X <<2>>
<<3>>id : XX<<4>>
<<5>>permission : A<<6>>
<<5>>permission : B<<6>>
<<0>>type : Uninstall<<1>>id : YY<<2>>
<<0>>type : New install<<1>>nom : Z<<2>>
...... 

in order to treat data in each data, I expect to seperate each of them to get this:

1 type: map
2 identify: xxx
-new loop-
1 type: contact
2 identify: yxy
3 state: install
-new loop-
1 type
...

and here is what I did:

while True:

  line = f.readline()

  search_type = re.findall(tag1+"(.*?)"+tag2, line) or re.findall(tag1+"(.*?)"+tag4, line)
  if search_type > [1]: 
    print search_type  
    f.readline()
    for line in f:
        print line
        if line.endswith(tag1,):
            print ' new loop'
            continue

  if len(line) == 0:
     break

but le result is like:

1 type: map
2 identify: xxx
1 type: contact
-new loop
2 identify: yxy
3 state: install
1 type
-new loop
...

the loops is not really correct. I will be grateful if anyone can sheds a light Thank you!

You have to print the line after printing ' new loop':

while True:
    line = f.readline()
    search_type = re.findall(tag1+"(.*?)"+tag2, line) or re.findall(tag1+"(.*?)"+tag4, line)

    if search_type > [1]: 
        print search_type  
        f.readline()
        for line in f:
            if line.endswith(tag1,):
                print ' new loop'                    
            print line

    if len(line) == 0:
        break

Unless I'm missing something, is it not enough to look for the substring '1 type'?

for line in f:
    if line.startswith('1 type'):
        print ' new loop'
    print line

I do not understand exactly what you mean. Maybe something like:

with open('test.txt','r') as fo:
    text = [ line.strip('\r\n') for line in fo]
    for item in text:
        if 'xxx' in item:
            do something

You could use a generator, that detects every 'chunk' and yields it (I understand, that condition is that the number on the beginning is smaller than before). Then you can iterate over those 'chunks' and over lines in each if necessary:

data = """1 type: map
2 identify: xxx
1 type: contact
2 identify: yxy
3 state: install
1 type"""

def read_in_chunks(data):
    last, chunk = None, []
    for line in data.splitlines():
        counter, sep, tail = line.partition(' ')
        try:
            counter = int(counter)
            # print counter, last
        except ValueError:
            continue
        if counter < last:
            # print 'chunk:', chunk
            yield chunk
            last, chunk = None, []
        last = counter
        chunk.append(line)
    yield chunk # return the last part

for chunk in read_in_chunks(data):
    print '\n'.join(chunk)
    print '-new loop-'

Output:

# 1 type: map
# 2 identify: xxx
# -new loop-
# 1 type: contact
# 2 identify: yxy
# 3 state: install
# -new loop-
# 1 type
# -new loop-

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM