【问题标题】:Comparing special characters in Python比较 Python 中的特殊字符
【发布时间】:2018-12-19 11:13:59
【问题描述】:

我有一个值为“操作”的字符串。在我的脚本中,我将读取一个文件并进行一些比较。在比较字符串时,我从同一源复制并放置在我的 python 脚本中的字符串不等于我在脚本中读取相同文件时收到的相同字符串。打印两个字符串都会给我“操作”。但是,当我将其编码为 utf-8 时,我注意到了不同之处。

  • b'Ope\xcc\x81rations'
  • b'Op\xc3\xa9rations'

我的问题是,在比较此类字符串时,如何确保我的 python 脚本中的特殊字符与文件内容相同。

【问题讨论】:

标签: python python-3.x python-2.7 character-encoding


【解决方案1】:

很高兴知道:

您在谈论两种类型的字符串,字节字符串和 unicode 字符串。每个都有将其转换为其他类型字符串的方法。 Unicode 字符串有一个产生字节的 .encode() 方法,而字节字符串有一个产生 unicode 的 .decode() 方法。意思是:

unicode.enocde() ----> 字节

bytes.decode() -----> unicode

UTF-8 无疑是最流行的 Unicode 存储和传输编码。它为每个代码点使用可变数量的字节。码位值越高,它在 UTF-8 中需要的字节数就越多。

切入正题:

如果将字符串重新定义为两个 Byte 字符串和 unicode 字符串,如下所示:

a_byte = b'Ope\xcc\x81rations'
a_unicode = u'Ope\xcc\x81rations'

b_byte = b'Op\xc3\xa9rations'
b_unicode = u'Op\xc3\xa9rations'

你会看到:

print 'a_byte lenght is: ', len(a_byte.decode("utf-8"))
#print 'a_unicode lenght is: ',len(a_unicode.encode("utf-8"))

print 'b_byte lenght is: ',len(b_byte.decode("utf-8"))
#print 'b_unicode lenght is: ', len(b_unicode.encode("utf-8"))

输出:

a_byte lenght is:  11
b_byte lenght is:  10

所以你看他们不一样。

我的解决方案:

如果你不想混淆,那么你可以使用repr(),同时打印a_byte,b_byte打印Opérations作为输出,但是:

print repr(a_byte),repr(b_byte)

将返回:

'Ope\xcc\x81rations','Op\xc3\xa9rations'

还可以将比较前的unicode归一化为@Daniel's answer,如下:

from unicodedata import normalize
from functools import partial
a_byte = 'Opérations'
norm = partial(normalize, 'NFC')
your_string = norm(a_byte.decode('utf8'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 2015-07-15
    • 2015-11-06
    • 2016-10-29
    • 1970-01-01
    • 2019-08-03
    • 1970-01-01
    相关资源
    最近更新 更多