python - 当包含空格时解析新行分隔的字符串

标签 python parsing

我正在使用非常简洁的 Parsy用于分割字符串的库(作为更大语法定义的一部分)。当没有嵌入空格时, sep_by 效果很好。基本上我想按换行符分割并获取所有字符,包括嵌入的空格或任何其他 Unicode 字符。示例:

作品:

>>> parser = letter.at_least(1).concat().sep_by(string('\n'))
>>> parser.parse('Smith\nFirefighter')
['Smith', 'Firefighter']

不起作用:

>>> parser.parse('John Smith\nFire fighter')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\code\Parsing\Parsing\env\lib\site-packages\parsy\__init__.py", line 90, in parse
    (result, _) = (self << eof).parse_partial(stream)
  File "C:\code\Parsing\Parsing\env\lib\site-packages\parsy\__init__.py", line 104, in parse_partial
    raise ParseError(result.expected, stream, result.furthest)
parsy.ParseError: expected one of 'EOF', '\n', 'a letter' at 0:4

我还想读取任何嵌入的 Unicode 字符,例如这个国际象棋符号:

>>> parser.parse('hello\u265ethere\nsir')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\code\Parsing\Parsing\env\lib\site-packages\parsy\__init__.py", line 90, in parse
    (result, _) = (self << eof).parse_partial(stream)
  File "C:\code\Parsing\Parsing\env\lib\site-packages\parsy\__init__.py", line 104, in parse_partial
    raise ParseError(result.expected, stream, result.furthest)
parsy.ParseError: expected one of 'EOF', '\n', 'a letter' at 0:5

任何见解将不胜感激。谢谢。声誉较高的人也可以创建 Parsy 标签吗?

最佳答案

到目前为止解决方案中存在的问题:

  • letter 仅匹配字母字符,而非所有字符
  • whitespace 匹配任何空白,所以如果你这样做 letter |空格它将消耗换行符,而不是在其上分割。

本质上你想要一个“除换行符之外的任何字符”解析器。最简单的方法是使用正则表达式:

>>> parser = regex(r"[^\n]+").sep_by(string('\n'))
>>> parser.parse("John Smith\nFirefigher")
['John Smith', 'Firefigher']

我通常发现使用 Parsy,正则表达式是构建最低级别部分的最简单方法。

关于python - 当包含空格时解析新行分隔的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55787731/

相关文章:

python - 有什么理由给 self 一个默认值吗?

algorithm - Delphi 中的数学表达式解析器?

python - 我可以为此使用 python ast 模块吗?

java - 使用apache common io读取大文件

python - 在Python中将 '**'替换为 'math.pow'

javascript - JavaScript 表达式 [1 [{}]] 究竟是如何解析的?

python - aws s3下载文件

python - Pyserial: "module ' serial' 没有属性 'tools' "

python - 安装graphviz,没有名为graphviz的模块

python - 动态规划 - 节省计算时间