使用 Python 查找和替换非 ascii 字符的正则表达式 [英] Regular expression that finds and replaces non-ascii characters with Python

查看:50
本文介绍了使用 Python 查找和替换非 ascii 字符的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一些非 ASCII 字符更改为_".例如,

<前>Tannh‰user -> Tannh_user

  • 如果我在 Python 中使用正则表达式,我该怎么做?
  • 不使用 RE 有没有更好的方法来做到这一点?

解决方案

针对 Python 3 进行了更新:

<预><代码>>>>'Tannh‰user'.encode().decode('ascii', 'replace').replace(u'\ufffd', '_')'Tannh___用户'

首先我们使用 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 with replace 将非ASCII字符翻译成'?',所以不知道有没有问题马克之前已经在那里了;请参阅 Ignacio Vazquez-Abrams 的解决方案.

<小时>

另一种方式,使用 ord() 并比较每个字符的值,如果它适合 ASCII 范围 (0-127) - 这适用于 unicode 字符串和 str:

<预><代码>>>>s = 'Tannh‰user' # 或 Python 2 中的 u'Tannh‰user'>>>>>>''.join(c if ord(c) <128 else '_' for c in s)'Tannh_user'

I need to change some characters that are not ASCII to '_'. For example,

Tannh‰user -> Tannh_user

  • If I use regular expression with Python, how can I do this?
  • Is there better way to do this not using RE?

解决方案

Updated for Python 3:

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

First we create byte string using encode() - it uses UTF-8 codec by default. If you have byte string then of course skip this encode step. Then we convert it to "normal" string using the ascii codec.

This uses the property of UTF-8 that all non-ascii characters are encoded as sequence of bytes with value >= 0x80.


Original answer – for Python 2:

How to do it using built-in str.decode method:

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

(You get unicode string, so convert it to str if you need.)

You can also convert unicode to str, so one non-ASCII character is replaced by ASCII one. But the problem is that unicode.encode with replace translates non-ASCII characters into '?', so you don't know if the question mark was there already before; see solution from Ignacio Vazquez-Abrams.


Another way, using ord() and comparing value of each character if it fits in ASCII range (0-127) - this works for unicode strings and for str in utf-8, latin and some other encodings:

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

这篇关于使用 Python 查找和替换非 ascii 字符的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆