使用Python查找和替换非ascii字符的正则表达式

时间:2010-05-03 14:54:45

标签: python regex

我需要将一些非ASCII的字符更改为“_”。 例如,

Tannh‰user -> Tannh_user
  • 如果我在Python中使用正则表达式,我该怎么做?
  • 有没有更好的方法可以不使用RE?

7 个答案:

答案 0 :(得分:9)

re.sub(r'[^\x00-\x7F]', '_', theString)

如果theString是unicode,或者ASCII编码占用0到0x7F(latin-1,UTF-8等)的编码中的字符串,这将有效。

答案 1 :(得分:5)

使用Python对字符编码的支持:

# coding: utf8
import codecs

def underscorereplace_errors(exc):
  return (u'_', exc.end)

codecs.register_error('underscorereplace', underscorereplace_errors)

print u'Tannh‰user'.encode('ascii', 'underscorereplace')

答案 2 :(得分:4)

针对Python 3进行了更新:

>>> 'Tannh‰user'.encode().decode('ascii', 'replace').replace(u'\ufffd', '_')
'Tannh___user'

首先我们使用encode()创建字节字符串 - 它默认使用UTF-8编解码器。如果你有字节字符串,那么当然跳过这个编码步骤。 然后我们使用ascii编解码器将其转换为“普通”字符串。

这使用UTF-8的属性,所有非ascii字符都被编码为值为> = 0x80的字节序列。


原始答案 - 适用于Python 2:

如何使用内置str.decode方法执行此操作:

>>> 'Tannh‰user'.decode('ascii', 'replace').replace(u'\ufffd', '_')
u'Tannh___user'

(您获得unicode字符串,如果需要,请将其转换为str。)

您还可以将unicode转换为str,因此一个非ASCII字符将替换为ASCII字符。但问题是unicode.encode replace将非ASCII字符转换为'?',因此您不知道问号是否已存在;见Ignacio Vazquez-Abrams的解决方案。


另一种方法,使用ord()并比较每个字符的值,如果它适合ASCII范围(0-127) - 这适用于unicode字符串和utf-8中的str ,拉丁语和其他一些编码:

>>> s = 'Tannh‰user' # or u'Tannh‰user' in Python 2
>>> 
>>> ''.join(c if ord(c) < 128 else '_' for c in s)
'Tannh_user'

答案 3 :(得分:2)

我宁愿在字符串中的每个字符上调用ord,1乘1.如果ord([char]) >= 128该字符不是ascii字符,应该被替换。

答案 4 :(得分:1)

如果您知道要替换哪些字符,则可以应用字符串方法

mystring.replace('oldchar', 'newchar')

答案 5 :(得分:1)

使用神奇的正则表达式[ -~]可以解决这个问题:

import re
re.sub(r"[^ -~]", "_", "Tannh‰user")
# 'Tannh_user'

说明:

  • ascii字符是符号ranging from " " to "~"-因此[ -~]会捕获所有ascii字符
  • 通过附加^,我们可以捕获所有非ASCII字符
  • 剩下的就是手续了

答案 6 :(得分:0)

回答问题

'[\u0080-\uFFFF]'

将匹配前128个字符以外的任何UTF-8字符

re.sub('[\u0080-\uFFFF]+', '_', x)

将用下划线替换任何连续的非ASCII字符序列

相关问题