【问题标题】:python - problems with regular expression and unicodepython - 正则表达式和 unicode 的问题
【发布时间】:2010-11-22 14:23:56
【问题描述】:

您好,我在 python 中遇到了问题。我试着用一个例子来解释我的问题。

我有这个字符串:

>>> string = 'ÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂÃ'
>>> print string
ÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂÃ

例如,我想将不同于 Ñ,Ã,ï 的字符替换为 ""

我试过了:

>>> rePat = re.compile('[^ÑÃï]',re.UNICODE)
>>> print rePat.sub("",string)
�Ñ�����������������������������ï�������������������Ã

我得到了这个�。 我认为这是因为 python 中的这种类型的字符由向量中的两个位置表示:例如 \xc3\x91 = Ñ。 为此,当我进行 regolar 表达式时,所有的 \xc3 都不会被替换。我怎么能做这种类型的子??????

谢谢 佛朗哥

【问题讨论】:

    标签: python regex unicode


    【解决方案1】:

    您需要确保您的字符串是 unicode 字符串,而不是纯字符串(纯字符串类似于字节数组)。

    例子:

    >>> string = 'ÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂÃ'
    >>> type(string)
    <type 'str'>
    
    # do this instead:
    # (note the u in front of the ', this marks the character sequence as a unicode literal)
    >>> string = u'\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff\xc0\xc1\xc2\xc3'
    # or:
    >>> string = 'ÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂÃ'.decode('utf-8')
    # ... but be aware that the latter will only work if the terminal (or source file) has utf-8 encoding
    # ... it is a best practice to use the \xNN form in unicode literals, as in the first example
    
    >>> type(string)
    <type 'unicode'>
    >>> print string
    ÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿÀÁÂÃ
    
    >>> rePat = re.compile(u'[^\xc3\x91\xc3\x83\xc3\xaf]',re.UNICODE)
    >>> print rePat.sub("", string)
    Ã
    

    从文件中读取时,string = open('filename.txt').read() 读取一个字节序列。

    要获取 unicode 内容,请执行以下操作:string = unicode(open('filename.txt').read(), 'encoding')。或者:string = open('filename.txt').read().decode('encoding')

    codecs 模块可以即时解码 unicode 流(例如文件)。

    用谷歌搜索python unicode。 Python unicode 处理一开始可能有点难以掌握,阅读它是值得的。

    我遵守这条规则:“软件只能在内部使用 Unicode 字符串,并在输出时转换为特定编码。” (来自http://www.amk.ca/python/howto/unicode

    我也推荐:http://www.joelonsoftware.com/articles/Unicode.html

    【讨论】:

      猜你喜欢
      • 2016-01-21
      • 2022-01-06
      • 1970-01-01
      • 2018-03-16
      • 2017-01-25
      • 2010-09-28
      • 2010-09-06
      • 2023-03-29
      • 1970-01-01
      相关资源
      最近更新 更多