【问题标题】:Extend "Python Template String" to Non-ASCII将“Python 模板字符串”扩展为非 ASCII
【发布时间】:2020-08-30 06:00:43
【问题描述】:

我正在尝试使用Python Template Strings 在公式字符串中填充值。该公式有时包含具有非 ASCII 字符的标识符,例如 α、ß、Γ 等。(请参阅 Unicode Greek and Coptic Chart。但根据 python 文档,模板字符串仅限于 ASCII 标识符。 与标识符匹配的默认正则表达式是(?a:[_a-z][_a-z0-9]*)

如何扩展默认正则表达式使其也匹配来自Unicode Greek and Coptic Chart 的字符?

【问题讨论】:

  • 理论上,您应该能够更改 Template.idpattern 以接受非 ASCII 标识符。实际上,这似乎不起作用。
  • 我也查过了。可能是因为在实例化过程中已经编译了模式。我使用以下方法来解决我的问题。 `from string import Template as _Templateclass Template(_Template):idpattern = r'([_a-z\u00D8-\u00F6\u00F8-\u00FF\u0370-\u03FF][_a-z\u00D8-\u00F6\u00F8-\u00FF\u0370-\u03FF0-9]*)'
  • 但是\u00D8-\u00F6\u00F8-\u00FF 不在您在问题中引用的列表中。您的意思是匹配任何 Unicode 字母吗?
  • @WiktorStribiżew 问题不在于如何为标识符编写正则表达式,而是如何让Template 识别它。
  • @DYZ 先生为您提供帮助。

标签: python python-3.x regex templates


【解决方案1】:

这就是我解决问题的方法。

from string import Template as _Template

    class Template(_Template):
        """Created a custom template class becasue default Template class doesn't support non ASCII identifiers"""
        idpattern = r'([_a-z\u0370-\u03FF][_a-z0-9\u0370-\u03FF]*)'

子类是必需的,因为python在类初始化期间编译了一个正则表达式模式,并且默认的Template.idpattern是固定的,如果在后期更改则无效。

【讨论】:

    猜你喜欢
    • 2018-05-26
    • 2011-10-15
    • 1970-01-01
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-20
    相关资源
    最近更新 更多