python - 使用sqlite在Django上实现重音不敏感搜索

标签 python django sqlite python-2.7

这个问题与我先前的问题Accent insensitive search django sqlite有关

正如回应中提到的那样,没有直接的方法可以这样做。我已经提出了一个解决方案,但是我不确定这是否是一个好的解决方案:

用例:假设数据库有一个表NewsArticles,其中一列是ArticleText。顾名思义,ArticleText包含新闻文章的文本,其中包含带有重音字符的几个单词。假设ArticleText中具有主键aid123的文章中出现的一个这样的单词是Puerto Aisén。现在,用户可以搜索Puerto AisénPuerto Aisen,并且应该能够找到找到的带重音字的粗体字(aid123),返回带有PK <b>Puerto Aisén</b>的文章。

解决方案:我在表normalizedArticleText中又增加了一列,并使其包含文本的unicode.normalize版本(删除了重音符号)。现在,无论何时出现搜索查询,我都首先使用s.decode('ascii')确定查询是否包含重音字符,然后在相应的列中进行相应的搜索。

问题:我正在复制整个数据。另外,如果搜索查询是该关键字的非重音版本,那么我也无法用粗体显示该重音关键字。

有什么好建议吗?我正在将sqlite与Django一起使用

最佳答案

尝试使用unicodedata包。这是Python 3的示例:

import unicodedata

unicodedata.normalize('NFD', 'répertoire').encode('ascii', 'ignore')


或者,对于Python 2.7:

import unicodedata

unicodedata.normalize('NFD', u'répertoire').encode('ascii', 'ignore')


这些将输出:

'repertoire'


只需将répertoire替换为您的字符串即可。 NFD是归一化的form。您可以在这里阅读更多有关标准化的不同形式的信息:

https://docs.python.org/3/library/unicodedata.html#unicodedata.normalize
https://docs.python.org/2/library/unicodedata.html#unicodedata.normalize

祝好运!

关于python - 使用sqlite在Django上实现重音不敏感搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31331629/

相关文章:

android - 编译时无法启动 Activity ,android.database.sqlite.SQLiteException : no such table,:SELECT * FROM table

ios - NSManagedObjectContext 保存在 SQLite 方面做什么?

python - 设置自定义轴值 pyplot

python - 对象不可逆Django是什么意思

Django render_to_string() 忽略 {% csrf_token %}

python - Django项目结构,

SQLite :"ALTER TABLE ` 游戏`ADD UNIQUE (`name` )"SQLite 错误

python - 为什么打印python时控制台有空间

python - 合并几个 Python 字典

python - 游戏代码中存在缩进问题