首页 > 解决方案 > 从 PyParsing 中的多行引用字符串中删除 \n

问题描述

我正在解析带有以下内容的多行引号字符串:

带有字符串的文件(test.txt):

PROPERTY PName "Multiline quoted 
string" ;

Python代码:

linebreak = pp.Suppress(';')
identifier = pp.Word(pp.alphanums + '._!<>/[]$')
qs = pp.QuotedString('"', multiline = True)

ifile = open("test.txt",'r')
test_string = ifile.read()
ifile.close()

PROPERTY = (pp.Suppress(pp.Keyword('PROPERTY'))
            + identifier('propName')
            + qs('propValue')
            + linebreak
           )

for t, s, e in PROPERTY.scanString(test_string):
    t.asDict()

产生:

"PROPERTY": {
        "propName": "PName",
        "propValue": "Multiline quoted \n   string"
      }

是否可以在解析期间删除 '\n' ?

标签: pythonpython-3.xpyparsing

解决方案


原来我找到了解决方案。它可以作为示例,因为用户指南中没有。

只需要escChar='\n'在 qs 中插入:

qs = pp.QuotedString('"', multiline = True, escChar='\n')

哪个产生:

"PROPERTY": {
        "propName": "PName",
        "propValue": "Multiline quoted    string"
      }

推荐阅读