【问题标题】:pyPEG2 parsing of newlinespyPEG2 解析换行符
【发布时间】:2015-10-20 21:35:05
【问题描述】:

我正在尝试使用pyPEG2 将 MoinMoin 标记转换为 Markdown,在某些情况下我需要注意换行符。但是,我什至无法让我的换行符解析测试工作。我是 pyPEG 新手,我的 Python 生锈了。请多多包涵。

代码如下:

#!/usr/local/bin/python3
from pypeg2 import *
import re

class Newline(List):
    grammar = re.compile(r'\n')

parse("\n", Newline)
parse("""
""", Newline)

这会导致:

Traceback (most recent call last):
  File "./pyPegNewlineTest.py", line 7, in <module>
    parse("\n", Newline)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pypeg2/__init__.py", line 667, in parse
    t, r = parser.parse(text, thing)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pypeg2/__init__.py", line 794, in parse
    raise r
  File "<string>", line 2

    ^
SyntaxError: expecting match on \n

就好像 pypeg 在 \n 之后插入了一个空行。

尝试其他选项,例如

    grammar = re.compile(r'\n', re.MULTILINE)
    grammar = re.compile(r'\r\n|\r|\n', re.MULTILINE)
    grammar = contiguous(re.compile(r'\r\n|\r|\n', re.MULTILINE))

并且这些组合的各种组合不会更改错误消息(尽管我认为我没有尝试所有组合)。将 Newline 更改为子类 str 而不是 List 也不会更改错误。

更新

我发现 pypeg 在解析之前会剥离换行符:

#!/usr/local/bin/python3
from pypeg2 import *                 
import re
class Newline(str):
    grammar = contiguous(re.compile(r'a'))

parse("\na", Newline)
parse("""
a""", Newline)

print("Success, of a sort.")

运行此结果:

Success, of a sort.

如果我覆盖Newlineparse 方法,我什至看不到换行符。它得到的第一件事是“a”。这与我在其他地方看到的一致。 pypeg 会去除所有前导空格,即使您指定 contiguous

所以,这就是正在发生的事情。不知道该怎么办。

【问题讨论】:

    标签: python newline pypeg


    【解决方案1】:

    是的,默认情况下 pypeg 删除包括换行符在内的空格。 这可以通过在parse() 函数中设置可选的whitespace 参数来轻松配置,例如在:

    parse("\na", Newline, whitespace=re.compile(r"[ \t\r]"))
    

    这样做仍然会跳过空格和制表符,但不会跳过换行符\n。 通过这个例子,解析器现在可以正确地找到语法错​​误:

    SyntaxError: expecting match on a
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-29
      • 2017-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多