簡體   English   中英

使python字符串等效性像SQL match一樣工作

[英]Getting python string equivalence to work like SQL match

我想匹配兩個字符串, Serhat Kılıçserhat kilic 在SQL中,這很容易,我可以這樣做:

select name from main_creditperson where name = 'serhat kılıç'
union all
select name from main_creditperson where name = 'serhat kilic';

===
name
Serhat Kılıç
Serhat Kılıç

換句話說,兩個名稱返回相同的結果。 我將如何在python中執行等效的字符串以查看這兩個名稱在SQL意義上是否“相同”。 我正在做類似的事情:

if name1 == name2:
   do_something()

我試着去unicodedata.normalize('NFKD', input_str)方式,但沒有得到我。 我該如何解決?

如果您對ASCII的所有內容都滿意,則可以檢查Python的“此Unicode的最佳ASCII”數據庫在哪里? Unidecode相當不錯,但是它是GPL許可的,這對於某些項目可能是個問題。 無論如何,它在您的情況下以及在很多其他情況下都可以工作,並且可以在Python 2和3上工作(它們來自Python 3,以便更輕松地了解發生的情況):

>>> from unidecode import unidecode
>>> unidecode('serhat kılıç')
'serhat kilic'
>>> unidecode('serhat kilic')
'serhat kilic'
>>> # as a bonus it does much more, like
>>> unidecode('北亰')
'Bei Jing '

我找到了這個

def compare_words (str_1, str_2):
    return unidecode(str_1.decode('utf-8')) == str_2

在Python 2.7上測試:

In[2]: from unidecode import unidecode
In[3]: def compare_words (str_1, str_2):
     return unidecode(str_1.decode('utf-8')) == str_2
 In[4]: print compare_words('serhat kılıç', 'serhat kilic')
 True

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM