Python 相同的字符不等于 [英] Python the same char not equals

查看:44
本文介绍了Python 相同的字符不等于的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库中有文本.我从 xhr 发送一些文本到我的视图.函数 find 没有找到一些 unicode 字符.

我想使用以下方法查找选定的文本:

text.find(selection)

但有时变量选择"包含这样的字符:

ę # in xhr unichr(281)

而在变量 'text' 中有:

ę # in db 有两个字符 unichr(101) + unichr(808)

它们只是同一事物的不同形式.如何让 .find 在这里更可靠地工作?

解决方案

这里 unicodedata.normalize 可能对你有帮助.

基本上,如果您将来自 db 的数据标准化,并将您的选择标准化为相同的形式,则在使用 str.findstr.__contains__(即in)、str.index 和朋友.

<预><代码>>>>u1 = chr(281)>>>u2 = chr(101) + chr(808)>>>打印(u1,u2)呸呸>>>u1 == u2错误的>>>unicodedata.normalize('NFC', u2) == u1真的

NFC 代表 Normal Form Composed 形式.您可以在此处阅读有关其他可能形式的一些说明.

I have text in my database. I send some text from xhr to my view. Function find does not find some unicode chars.

I want to find selected text using:

text.find(selection)

but sometimes variable 'selection' contains a char like that:

ę  # in xhr unichr(281)

whereas in variable 'text' there was:

ę  # in db has two chars unichr(101) + unichr(808)

They are just different forms of the same thing. How to make .find work more reliably here?

解决方案

Here unicodedata.normalize might help you.

Basically if you normalize the data coming from the db, and normalize your selection to the same form, you should have a better result when using str.find, str.__contains__ (i.e. in), str.index, and friends.

>>> u1 = chr(281)
>>> u2 = chr(101) + chr(808)
>>> print(u1, u2)
ę ę
>>> u1 == u2
False
>>> unicodedata.normalize('NFC', u2) == u1
True

NFC stands for the Normal Form Composed form. You can read up here for some description of the other possible forms.

这篇关于Python 相同的字符不等于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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