Skip to main content
 首页 » 编程设计

python之从字符串中删除变音符号以实现搜索功能

2025年05月04日23mfryf

我正在用Django开发一个简单的网页,我需要实现搜索功能。我目前正在使用这样的东西:

search_box = request.GET['search_box'] 
X = Foo.objects.filter(Q(title__contains=search_box) | Q(info__contains=search_box)).values() 

如果指定的列包含搜索字符串,它会检查我的数据库,但是如果我搜索“kočík”但我的数据库包含“kocik”怎么办。我如何从 Python 3 中的字符串中删除变音符号,或者实现它的最佳方法是什么?谢谢

请您参考如下方法:

你可以为此使用 unicodedata 包。

import unicodedata 
def shave_marks(txt): 
    """This method removes all diacritic marks from the given string""" 
    norm_txt = unicodedata.normalize('NFD', txt) 
    shaved = ''.join(c for c in norm_txt if not unicodedata.combining(c)) 
    return unicodedata.normalize('NFC', shaved) 

关于这个算法的一些细节:

变音符号的主要问题是,在 UTF-8 中,一些组合字符会修改前面的字符,而另一些则包含在字符中。例如,'café' 和 'cafe/u0301' 看起来一样。

来自 https://docs.python.org/2/library/unicodedata.html :

Even if two unicode strings are normalized and look the same to a human reader, if one has combining characters and the other doesn’t, they may not compare equal.

该算法首先分解一个字符串(使用'NFD'方法),使所有变音符号成为组合字符,然后过滤掉所有组合字符,最后组成字符串(使用'NFC'方法)。