Python 从PyParsing中的多行引号字符串中删除\n
我正在用以下内容分析一个多行带引号的字符串: 包含字符串(test.txt)的文件: Python代码:Python 从PyParsing中的多行引号字符串中删除\n,python,python-3.x,pyparsing,Python,Python 3.x,Pyparsing,我正在用以下内容分析一个多行带引号的字符串: 包含字符串(test.txt)的文件: 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(
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()
是否可以在分析期间删除“\n” 结果是我找到了解决办法。它可以作为一个例子,因为在用户指南中没有 只需在qs中插入
escChar='\n'
:
qs = pp.QuotedString('"', multiline = True, escChar='\n')
这将产生:
"PROPERTY": {
"propName": "PName",
"propValue": "Multiline quoted string"
}
这并不是
escChar
参数的真正目的,而是指示如何转义通常是引号分隔符的嵌入字符
我认为最好使用parse操作来处理这一点,parse操作是一个解析时间回调,可以在解析令牌之后,但在它们返回给调用方之前修改它们。这是作为控制台会话的代码,将解析操作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'], {})], {})
成功解析
qs
后,将调用remove\u newlines
方法,并将生成的标记作为t
参数传递给该方法。我们可以就地修改这些令牌。在这个方法中,换行符被替换为空字符串,然后重新分配到标记中,对它们进行适当的修改。Hello@Paul,我知道如何使用这个方法。我认为在使用回调之前有一些捷径。既然你说escChar
不应该以这种方式使用,我是否应该删除我的答案?是否有某种pp.Suppress()来执行此操作?创建一个函数来替换一个字符似乎太多了。您可以使用qs.setParseAction(lambda t:t[0].replace('\n','')
将其折叠为lambda。但是为这种操作编写解析操作并没有冒犯我的感情。
"PROPERTY": {
"propName": "PName",
"propValue": "Multiline quoted string"
}
>>> 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'], {})], {})