Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 非ASCII字符的Regexp_Python_Regex_Unicode_Python 3.x - Fatal编程技术网

Python 非ASCII字符的Regexp

Python 非ASCII字符的Regexp,python,regex,unicode,python-3.x,Python,Regex,Unicode,Python 3.x,考虑在Python 3中使用正则表达式的这个代码段: >>> t = "Meu cão é #paraplégico$." >>> re.sub("[^A-Za-z0-9 ]","",t,flags=re.UNICODE) 'Meu co paraplgico' 为什么要删除非ASCII字符?我试着不用国旗,一切都一样 作为奖励,任何人都可以在Python 2.7上实现这一点吗?您正在将非字母数字字符([^a-Za-z0-9])替换为空白(“)。非ASCI

考虑在Python 3中使用正则表达式的这个代码段:

>>> t = "Meu cão é #paraplégico$."
>>> re.sub("[^A-Za-z0-9 ]","",t,flags=re.UNICODE)
'Meu co  paraplgico'
为什么要删除非ASCII字符?我试着不用国旗,一切都一样


作为奖励,任何人都可以在Python 2.7上实现这一点吗?

您正在将非字母数字字符(
[^a-Za-z0-9]
)替换为空白(
)。非ASCII字符不在A-Z、A-Z或0-9之间,因此它们会被替换

您可以像这样匹配所有单词字符:

>>> t = "Meu cão é #paraplégico$."
>>> re.sub("[^\w ]","",t, flags=re.UNICODE)
>>> 'Meu cão é paraplégico'

或者,您可以像这样将字符添加到正则表达式中:
[^A-Za-z0-9ã]

您正在用空白(
[^A-Za-z0-9]
)替换非字母数字字符(
[^A-Za-z0-9]
)。非ASCII字符不在A-Z、A-Z或0-9之间,因此它们会被替换

[In 1]: import regex
[In 2]: t = u"Meu cão é #paraplégico$."
[In 3]: regex.sub(r"[^\p{Alpha} ]","",t,flags=regex.UNICODE)
[In 4]: print(regex.sub(r"[^\p{Alpha} ]","",t,flags=regex.UNICODE))
您可以像这样匹配所有单词字符:

>>> t = "Meu cão é #paraplégico$."
>>> re.sub("[^\w ]","",t, flags=re.UNICODE)
>>> 'Meu cão é paraplégico'
或者您可以像这样将字符添加到正则表达式中:
[^A-Za-z0-9ãé]

[In 1]: import regex
[In 2]: t = u"Meu cão é #paraplégico$."
[In 3]: regex.sub(r"[^\p{Alpha} ]","",t,flags=regex.UNICODE)
[In 4]: print(regex.sub(r"[^\p{Alpha} ]","",t,flags=regex.UNICODE))
Meu cãoéParalégico

Meu cãoéParalégico


我通过切换到regex库(从PyPI)解决了这个问题

然后,regex命令变成:

regex.sub(ur"[^\p{L}\p{N} ]+", u"", t)

我通过切换到regex库(从PyPI)解决了这个问题

然后,regex命令变成:

regex.sub(ur"[^\p{L}\p{N} ]+", u"", t)

我使用的是python 3.2,因为
a-z
abcdef…xyz
,这不包括
a
。如果您想要所有单词字符,请使用
\w
。我使用的是python 3.2,因为
a-z
abcdef…xyz
,而这不包括
a
。如果您想要所有单词字符,请使用
\w
。是的,我知道了!但是在Unicode中A-Za-z的等价物是什么?在许多(其他)语言中,您可以使用Unicode属性定义
[^\p{Alpha}]
的正则表达式。请参阅Python中的备选方案。是的,我知道了!但是在Unicode中A-Za-z的等价物是什么?在许多(其他)语言中,您可以使用Unicode属性定义
[^\p{Alpha}]
的正则表达式。有关Python中的替代方案,请参见。