3

我需要評估unicode字符串上的levenshtein編輯距離,這意味着包含相同內容的兩個字符串需要進行歸一化處理以避免偏移編輯距離。爲什麼我不能規範化這個隨機unicode字符串?

這裏是我爲我的測試,隨機Unicode字符串:

def random_unicode(length=10): 
    ru = lambda: unichr(random.randint(0, 0x10ffff)) 
    return ''.join([ru() for _ in xrange(length)]) 

這裏是失敗的簡單的測試案例:

import unicodedata 
uni = random_unicode() 
unicodedata.normalize(uni, 'NFD') 

,這裏是錯誤:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-9: ordinal not in range(128) 

我檢查確認uni實際上是一個unicode對象:

u'\U00020d93\U000fb2e6\U0005709a\U000bc31e\U00080262\U00034f00\U00059941\U0002dd09\U00074f6d\U0009ef7a' 

有人能賜教嗎?

+0

輸入參數反轉。 –

回答

5

您已切換參數normalize。從the relevant documentation

unicodedata.normalize(form, unistr)

Return the normal form form for the Unicode string * unistr*. Valid values for form are ‘NFC’, ‘NFKC’, ‘NFD’, and ‘NFKD’.

第一參數是的形式,並且所述是被歸一化的字符串。這工作得很好:

unicodedata.normalize('NFD', uni) 
+0

...我是個白癡。謝謝!真的應該有一個斷言錯誤或明確指出,第一個參數需要一個unicode字符串= /「什麼可能出錯會出錯」,因爲他們說... – blz

+0

有趣的是,python不告訴你,參數一個不是一個有效的正常形式... – Sebastian