【问题标题】:Pyparsing for unicode letters对 unicode 字母进行 Pyparsing
【发布时间】:2020-03-25 03:40:39
【问题描述】:

我需要对 unicode 字符使用 pyparsing。所以我从他们的 github 存储库中尝试了带有法语字符 cédille 的简单示例并给出了错误。

我的代码

from pyparsing import Word, alphas
greet = Word(alphas) + "," + Word(alphas) + "!"
hello = "Hello, cédille!"
greet.parseString(hello)

它给出了错误

pyparsing.ParseException: Expected "!" (at char 8), (line:1, col:9)

有没有办法解决这个问题?

【问题讨论】:

  • alphas 似乎只是纯 ASCII。有一个定义 alphas8bit 要么命名错误,要么也没有帮助。
  • alphas8bit 可以追溯到早期的 Python2 时代,当时添加了 128-255 个字母字符(设置了 bit8,因此得名)。

标签: python unicode pyparsing


【解决方案1】:

Pyparsing 具有 pyparsing_unicode 模块,该模块定义了许多 unicode 字符范围,每个范围内都有 alphasnums 等的定义。范围包括CJKCyrillicDevanagariHebrewArabic 等。示例目录中的 greetingInGreek.pygreetingInKorean.py 示例展示了其中的几个。

您的示例使用 Latin1 集,如下所示:

from pyparsing import Word, pyparsing_unicode as ppu
intl_alphas = ppu.Latin1.alphas
greet = Word(intl_alphas) + "," + Word(intl_alphas) + "!"
hello = "Hello, cédille!"
print(greet.parseString(hello))

打印:

['Hello', ',', 'cédille', '!']

alphas8bit 可能会保留用于旧版支持,但新应用程序应使用pyparsing_unicode.Latin1.alphas

【讨论】:

  • 在 python 2.7 中这仍然给出错误pyparsing.ParseException: Expected "!", found '\xa9' (at char 9), (line:1, col:10)
  • 您好像忘记声明源文件的编码,或者未能将字符串标记为 Unicode 字符串。
【解决方案2】:

alphas 显然只是英文/纯 ASCII。以下似乎有效:

from pyparsing import Word, alphas, alphas8bit
greet = Word(alphas+alphas8bit) + "," + Word(alphas+alphas8bit) + "!"
hello = "Hello, cédille!"
greet.parseString(hello)

这是 Unicode,因此字符 é 没有什么特别“8 位”的;但是,如果文档至少大致正确,我想它仍然会被略带异国情调的重音字符打破(Latin-1 中不可用的任何内容,如捷克或波兰重音字符,或者走极端并尝试越南语)。

也许探索unicodedata 模块以获取“字母”字符的正确枚举,或找到正确公开此Unicode 功能的第三方模块。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2010-11-09
  • 2016-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-14
  • 2012-10-16
相关资源
最近更新 更多