【问题标题】:Implementing accent insensitive search on django using sqlite使用 sqlite 在 django 上实现重音不敏感搜索
【发布时间】:2015-09-28 15:55:16
【问题描述】:

这个问题和我之前的问题Accent insensitive search django sqlite有关

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

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

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

问题:我正在复制整个数据。此外,如果搜索查询是关键字的非重音版本,我无法将重音关键字加粗。

有什么绝妙的建议吗?我正在使用带有 sqlite 的 django

【问题讨论】:

    标签: python django sqlite python-2.7


    【解决方案1】:

    尝试使用 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

    祝你好运!

    【讨论】:

      猜你喜欢
      • 2015-09-28
      • 2010-10-21
      • 1970-01-01
      • 1970-01-01
      • 2012-09-19
      • 1970-01-01
      • 2017-08-21
      • 2011-11-22
      • 1970-01-01
      相关资源
      最近更新 更多