我编写了一个程序,用于向Python正则表达式添加(有限的)Unicode支持,虽然它在CPython 2.5.2上运行良好,但在PyPy(1.5.0-alpha0 1.8.0,实现Python 2.7.1 2.7.2)上无法工作,两者都在Windows XP上运行(编辑:如评论中所述,@dbaupp可以在Linux上成功运行)。我不知道原因,但我怀疑这与我的使用
(在PyPy上,“示例用法”中没有匹配项,因此
u"
和ur"
有关。完整源代码在此处,相关部分如下:# -*- coding:utf-8 -*-
import re
# Regexps to match characters in the BMP according to their Unicode category.
# Extracted from Unicode specification, version 5.0.0, source:
# http://unicode.org/versions/Unicode5.0.0/
unicode_categories = {
ur'Pi':ur'[\u00ab\u2018\u201b\u201c\u201f\u2039\u2e02\u2e04\u2e09\u2e0c\u2e1c]',
ur'Sk':ur'[\u005e\u0060\u00a8\u00af\u00b4\u00b8\u02c2-\u02c5\u02d2-\u02df\u02...',
ur'Sm':ur'[\u002b\u003c-\u003e\u007c\u007e\u00ac\u00b1\u00d7\u00f7\u03f6\u204...',
...
ur'Pf':ur'[\u00bb\u2019\u201d\u203a\u2e03\u2e05\u2e0a\u2e0d\u2e1d]',
ur'Me':ur'[\u0488\u0489\u06de\u20dd-\u20e0\u20e2-\u20e4]',
ur'Mc':ur'[\u0903\u093e-\u0940\u0949-\u094c\u0982\u0983\u09be-\u09c0\u09c7\u0...',
}
def hack_regexp(regexp_string):
for (k,v) in unicode_categories.items():
regexp_string = regexp_string.replace((ur'\p{%s}' % k),v)
return regexp_string
def regex(regexp_string,flags=0):
"""Shortcut for re.compile that also translates and add the UNICODE flag
Example usage:
>>> from unicode_hack import regex
>>> result = regex(ur'^\p{Ll}\p{L}*').match(u'áÇñ123')
>>> print result.group(0)
áÇñ
>>>
"""
return re.compile(hack_regexp(regexp_string), flags | re.UNICODE)
(在PyPy上,“示例用法”中没有匹配项,因此
result 为 None )
重申一下,程序在CPython上运行良好:Unicode数据似乎正确,替换按预期工作,使用示例通过 doctest 和直接在命令行中键入都可以正常运行。源文件编码也是正确的,并且Python中的 coding 指令似乎被识别。
有什么想法可以解决PyPy破坏我的代码的“不同”?许多事情浮现在我脑海中(无法识别的 coding 头,命令行中不同的编码,对 r 和 u 的不同解释),但就我的测试而言,CPython和PyPy似乎表现相同,因此我对下一步该尝试什么毫无头绪。
[PyPy 1.8.0 with GCC 4.4.3] on linux2
,给出的示例对我来说运行良好。因此,下一步要尝试的是升级您的PyPy。 - huoncodecs
正确加载的文件时,存在不一致的行为。 - mgibsonbr