从 PyParsing 中的多行引用字符串中删除 \n

Remove \n from multiline quoted string in PyParsing

我正在使用以下内容解析多行引用字符串:

包含字符串 (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'?

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

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

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

产量:

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

这并不是 escChar 参数的真正用途,它是指示如何转义通常为引号定界符的嵌入字符。

这是我认为最好用解析操作处理的更多内容,解析操作是一个解析时回调,可以在解析后立即修改标记,但在它们返回给调用者之前。这是您作为控制台会话的代码,将解析操作 remove_newlines 添加到 qs:

>>> text = """PROPERTY PName "Multiline quoted 
... string" ;"""
>>> import pyparsing as pp

>>> qs = pp.QuotedString('"', multiline=True)

>>> qs.searchString(text)
([(['Multiline quoted \nstring'], {})], {})

>>> def remove_newlines(t):
...     t[0] = t[0].replace('\n', '')
...     
>>> qs.addParseAction(remove_newlines)

>>> qs.searchString(text)
([(['Multiline quoted string'], {})], {})

remove_newlines 方法在 qs 成功解析后调用,结果标记作为 t 参数传递给该方法。我们可以就地修改这些标记。在此方法中,换行符被替换为空字符串,然后分配回标记,就地修改它们。