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