如何在Parsley PEG语法中替换换行符后跟空格

时间:2014-06-12 15:09:31

标签: python parsing peg

所有 我正在通过编写解析vCard格式的解析器来学习Parsley。我的问题是vCard格式的某些行可能会分成几行。使用RFC 822“折叠”技术的多行表示。也就是说,只要存在线性白色空间,CRLF紧接着至少有一个LWSP-char。 我的解决方案是首先解析原始文本,在那里我可以找到换行符后跟空格并加入那些行。但是我无法让它工作:我最近的尝试: 代码返回最后的错误: TypeError:+:'bool'和'str

的不支持的操作数类型
import parsley
my_newline = "\n"
space = " "

def isLogicalLine(txt=""): #Function called from Parsley, just search for newline followed by space
    result = True
    if txt[:-2] == my_newline+space:
        result = False
    return result

tst_line2 = parsley.makeGrammar("""
CRLF = '\n' 
line = (~(CRLF) anything+:x ?(isLogicalLine(x))):first_part  -> first_part+ ' test '
""", {"isLogicalLine":isLogicalLine})
# ~(CRLF) = NOT CRLF
# ?(isLogicalLine(x)) = python expression that is true or false
# -> first_part+ ' test ' == modify result by Python express

test_string = "BEGIN:VCARD"+my_newline+"VERSION:2.1"+my_newline+\
              "N;CHARSET=UTF-8;ENCODING=8BIT:Bab"+my_newline+\
              "TEL;PREF;VOICE;ENCODING=8BIT:123456789"+my_newline+"END:VCARD"+\
              my_newline+" END:VCARD"

print(tst_line2(test_string).line())

1 个答案:

答案 0 :(得分:0)

您可以通过将测试移出绑定来修复它,如下所示:

line = (~(CRLF) anything+:x):first_part ?(isLogicalLine(x)) -> first_part + ' test '

不确定是否是错误,但first_part被绑定到isLogicalLine测试的结果,因此first_part + ' test '试图添加bool和a字符串。

相关问题