Python 中 UTF-8 编码的坑:字符串多种表示方法

发布于 2023-01-28 15:52:35 字数 1695 浏览 95 评论 0

UTF-8 中定义了一些组合字符,这些字符会与它前面的非组合字符组合显示成一个字符,一般用它来添加加重或者变音标记。

同时呢,某些常用的加重字符也会有自己的单一编码值,这些字符叫做预组合字符(precomposed characters)。

这就带来一个很恐怖的后果,某些 UTF-8 的字符可能有两种表示方法!例如单词 naïve 可以写作这6个字符 nai\u0308ve ,也可能写作5个字符 na\u00EFve。这样一来,在程序中处理这类字符时就会出现一些很诡异的结果:

例如下面这段 python 代码

import re
s1 = "nai\u0308ve"
s2 = "na\u00EFve"

if s1 == s2:
    print(s1,"is equal to",s2)
else:
    print(s1,"is not equal to",s2)

regexp = '^.....$'
if re.match(regexp,s1):
    print(regexp,"is matching",s1)
else:
    print(regexp,"is not matching",s1)

if re.match(regexp,s2):
    print(regexp,"is matching",s2)
else:
    print(regexp,"is not matching",s2)

print("length of",s1,"is",len(s1))
print("length of",s2,"is",len(s2))

结果为:

naïve is not equal to naïve
^.....$ is not matching naïve
^.....$ is matching naïve
length of naïve is 6
length of naïve is 5

解决方法是用 unicodedata 库中的 normalize 函数来对字符串进行归一化(normalization)

import re
from unicodedata import normalize
s1 = normalize('NFC',"nai\u0308ve")
s2 = normalize('NFC',"na\u00EFve")

if s1 == s2:
    print(s1,"is equal to",s2)
else:
    print(s1,"is not equal to",s2)

regexp = '^.....$'
if re.match(regexp,s1):
    print(regexp,"is matching",s1)
else:
    print(regexp,"is not matching",s1)

if re.match(regexp,s2):
    print(regexp,"is matching",s2)
else:
    print(regexp,"is not matching",s2)

print("length of",s1,"is",len(s1))
print("length of",s2,"is",len(s2))

其结果为

naïve is equal to naïve
^.....$ is matching naïve
^.....$ is matching naïve
length of naïve is 5
length of naïve is 5

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

半﹌身腐败

暂无简介

文章
评论
26 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文