【问题标题】:Removing non-ascii characters from any given stringtype in Python从 Python 中的任何给定字符串类型中删除非 ascii 字符
【发布时间】:2011-04-09 17:36:10
【问题描述】:
>>> teststring = 'aõ'
>>> type(teststring)
<type 'str'>
>>> teststring
'a\xf5'
>>> print teststring
aõ
>>> teststring.decode("ascii", "ignore")
u'a'
>>> teststring.decode("ascii", "ignore").encode("ascii")
'a'

这是我真正希望它在我删除非 ascii 字符时在内部存储的内容。为什么 decode("ascii 会给出一个 unicode 字符串?

>>> teststringUni = u'aõ'
>>> type(teststringUni)
<type 'unicode'>
>>> print teststringUni
aõ
>>> teststringUni.decode("ascii" , "ignore")

Traceback (most recent call last):
  File "<pyshell#79>", line 1, in <module>
    teststringUni.decode("ascii" , "ignore")
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf5' in position 1: ordinal not in range(128)
>>> teststringUni.decode("utf-8" , "ignore")

Traceback (most recent call last):
  File "<pyshell#81>", line 1, in <module>
    teststringUni.decode("utf-8" , "ignore")
  File "C:\Python27\lib\encodings\utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf5' in position 1: ordinal not in range(128)
>>> teststringUni.encode("ascii" , "ignore")
'a'

这又是我想要的。 我不明白这种行为。有人可以向我解释这里发生了什么吗?

编辑:我认为这会让我理解一些事情,这样我就可以解决我在这里陈述的真正的程序问题: Converting Unicode objects with non-ASCII symbols in them into strings objects (in Python)

【问题讨论】:

    标签: python string unicode replace non-ascii-characters


    【解决方案1】:

    为什么 decode("ascii") 会给出一个 unicode 字符串?

    因为这就是decode 的作用:它将像您的 ASCII 一样的字节字符串解码为 un​​icode。

    在你的第二个例子中,你试图“解码”一个已经是 unicode 的字符串,它没有任何效果。但是,要将其打印到您的终端,Python 必须将其编码为您的默认编码,即 ASCII - 但由于您没有明确完成该步骤,因此没有指定“忽略”参数,它会引发错误无法对非 ASCII 字符进行编码。

    所有这一切的诀窍是记住decode 接受编码的字节串并将其转换为Unicode,而encode 则相反。如果您了解 Unicode 不是编码,可能会更容易。

    【讨论】:

    • 嗯,你是对的,除了一些细节。由于他可以正确打印'a\xf5',因此他的终端编码不是ascii,而是.. 别的东西。控制台编码是一个非常常见的问题,但这次并非如此。此外,teststringUni.decode("ascii" , "ignore") 在您尝试打印结果时不会失败。它告诉 Python teststringUni 是一个 ascii 编码的字符串(它显然是 unicode,但 Python 信任用户)并尝试对其进行解码 - 这无法正常工作。
    • 是的,我认为这就是问题所在:我的终端编码是什么?仅仅因为对象类型是字符串并不意味着编码是 ascii,我明白这一点。我现在的问题是弄清楚如何将 unicode 类型的东西翻译成终端的字符串类型,同时保留所有信息。
    【解决方案2】:

    很简单:.encode 将 Unicode 对象转换为字符串,.decode 将字符串转换为 Unicode。

    【讨论】:

    • 如果这不起作用,也尝试使用 BeautifulSoup(html).encode for html 或 regex 模块
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    • 2012-01-21
    • 1970-01-01
    • 2011-02-14
    • 2023-03-18
    相关资源
    最近更新 更多