1

Input:

@example1
abcd
efg
hijklmnopq
@example2
123456789

Script:

def parser_function(f):
    name = ''
    body = ''   
    for line in f:  
        if len(line) >= 1:
            if line[0] == '@':
                name = line  
                continue 
            body = body + line  
            yield name,''.join(body)

for line in parser_function(data_file):
    print line 

Output

('@example1', 'abcd')
('@example1', 'abcdefg')
('@example1', 'abcdefghijklmnopq')
('@example2', 'abcdefghijklmnopq123456789')

Desired Output:

('@example1', 'abcdefghijklmnopq')
('@example2', '123456789')

My problem, my generator is yielding every line but i'm not sure where to reset the line. i'm having trouble getting the desired output and i've tried a few different ways. any help would be greatly appreciated. saw some other generators that had "if name:" but they were fairly complicated. I got it to work using those codes but i'm trying to make my code as small as possible

1 Answer 1

4

You need to change where you yield:

def parser_function(f):
    name = None
    body = ''    
    for line in f:  
        if line and line[0] == '@':
            if name:
                yield name, body
            name = line
        else:
            body += line  
    if name:
        yield name, body

This yields once before every @... and once at the end.

P.S. I've renamed str to body to avoid shadowing a built-in.

Sign up to request clarification or add additional context in comments.

4 Comments

might be worth pointing out not to use str as a variable name
@PadraicCunningham: Good point, let me add this to the answer. Thanks.
what is the "if line and line[0] == '@'" I understand the line[0] but wouldn't the "if line" always be True?
@draconisthe0ry: In essence, if line checks whether the line is not empty (so that we don't try to do line[0] on an empty line).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.