解析多个标识符

时间:2014-12-05 23:20:38

标签: python parsing generator

我试图从Generator not working to split string by particular identifier . Python 2实现这段代码,但我发现其中有两个我似乎无法修复的错误。

Input:
@m120204
CTCT
+
~@@!
@this_one_has_an_at_sign
CTCTCT
+
@jfik9
@thisoneisempty

+


#empty line after + and then empty line to end file (2 empty lines)

这两个错误是:     (i)当有一个@在'+'行后面开始代码行,例如第二个条目(@this_one_has_an_at_sign)     (ii)当@identification_line后面的行或'+'行后面的行是空的时,如第3个条目(@thisoneisempty)

我希望输出与我引用的帖子相同:

yield (name, body, extra)

在@this_one_has_an_at_sign

的情况下
name= this_one_has_an_at_sign 
body= CTCTCT
quality= @jfik9

在@thisoneisempty

的情况下
name= thisoneisempty
body= ''
quality= ''

我尝试使用标志,但我似乎无法解决这个问题。我知道如何在不使用发电机的情况下这样做,但我将使用大文件,所以我不想走这条路。我目前的代码是:

def organize(input_file):
    name = None
    body = ''
    extra = ''
    for line in input_file:
        line = line.strip()
        if line.startswith('@'):
            if name:
                body, extra = body.split('+',1)
                yield name, body, extra
                body = ''
            name = line
        else:
            body = body + line
    body, extra = body.split('+',1)
    yield name, body, extra

for line in organize(file_path):
    print line

0 个答案:

没有答案