Confusion from executing multiple loops:

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dechen
    New Member
    • Jan 2010
    • 8

    Confusion from executing multiple loops:

    I have an input in the form (as given below) in a text file. I have to loop through the contents in between two '$-$-$-$' characters. This is done by splitting at '$-$-$-$'. To get the Output as shown in the format below I could achieve by splitting at newline and at '-' character and looping through. Problem is I cannot get the names iteratively like 1.lab, 2.lab, 3.lab for content b/w $-$-$-$. Couldn't apply the loops properly. Confused with the loops. Please help me construct the loops properly so that I can get the file names (1.lab, 2.lab, etc.) iteratively/ automatically.

    Thanks.

    INPUT
    $-$-$-$
    m-i-x-0
    ph-e-l-0
    $-$-$-$
    n-o-r-0
    s-e-m-0
    c-e-n-0
    $-$-$-$

    OUTPUT
    "1.lab"
    m0
    i0
    ph0
    e0
    l0
    .
    "2.lab"
    n0
    o0
    r0
    s0
    e0
    m0
    c0
    e0
    n0
    .
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Where do the names '1.lab' and '2.lab' come from? Are they names of text files or labels for the output? If labels for output:
    Code:
    fn = 'lab_data.txt'
    
    s = open(fn).read()
    sList = [[s for s in item.split('\n') if s] for item in s.split('$-$-$-$') if item]
    
    output = []
    
    for i, item in enumerate(sList):
        output.append(['"%d.lab"' % (i+1), ])
        for elem in item:
            subList = elem.split('-')
            num = subList.pop(-1)
            for s in subList:
                output[i].append("%s%s" % (s, num))
    
    print '\n.\n'.join(['\n'.join(item) for item in output])
    Output:
    Code:
    >>> "1.lab"
    m0
    i0
    x0
    ph0
    e0
    l0
    .
    "2.lab"
    n0
    o0
    r0
    s0
    e0
    m0
    c0
    e0
    n0
    >>>

    Comment

    • dechen
      New Member
      • Jan 2010
      • 8

      #3
      Thank you very much. :-)

      Comment

      Working...