2009-05-30 64 views
5

我有一個完整的類似名稱的數據庫:Python字符串清理+操作(重音字符)

John Smith 
Scott J. Holmes 
Dr. Kaplan 
Ray's Dog 
Levi's 
Adrian O'Brien 
Perry Sean Smyre 
Carie Burchfield-Thompson 
Björn Árnason 

有需要被轉換爲字符串與非重音字符幾個外國名字帶有重音在其中。

我想轉換的全名(剝字符,如 「'」, 「 - 」 後),以用戶登錄,如:

john.smith 
scott.j.holmes 
dr.kaplan 
rays.dog 
levis 
adrian.obrien 
perry.sean.smyre 
carie.burchfieldthompson 
bjorn.arnason 

到目前爲止,我有:

Fullname.strip() # get rid of leading/trailing white space 
Fullname.lower() # make everything lower case 


... # after bad chars converted/removed 
Fullname.replace(' ', '.') # replace spaces with periods 
+1

這是**邪惡**,並總結冒犯,以毀壞所有這些字符。如果你這樣做,你甚至無法正確寫英文。 ASCII已死! – tchrist 2010-11-13 18:49:16

回答

12

從頁面

def latin1_to_ascii (unicrap): 
    """This replaces UNICODE Latin-1 characters with 
    something equivalent in 7-bit ASCII. All characters in the standard 
    7-bit ASCII range are preserved. In the 8th bit range all the Latin-1 
    accented letters are stripped of their accents. Most symbol characters 
    are converted to something meaningful. Anything not converted is deleted. 
    """ 
    xlate = { 
     0xc0:'A', 0xc1:'A', 0xc2:'A', 0xc3:'A', 0xc4:'A', 0xc5:'A', 
     0xc6:'Ae', 0xc7:'C', 
     0xc8:'E', 0xc9:'E', 0xca:'E', 0xcb:'E', 
     0xcc:'I', 0xcd:'I', 0xce:'I', 0xcf:'I', 
     0xd0:'Th', 0xd1:'N', 
     0xd2:'O', 0xd3:'O', 0xd4:'O', 0xd5:'O', 0xd6:'O', 0xd8:'O', 
     0xd9:'U', 0xda:'U', 0xdb:'U', 0xdc:'U', 
     0xdd:'Y', 0xde:'th', 0xdf:'ss', 
     0xe0:'a', 0xe1:'a', 0xe2:'a', 0xe3:'a', 0xe4:'a', 0xe5:'a', 
     0xe6:'ae', 0xe7:'c', 
     0xe8:'e', 0xe9:'e', 0xea:'e', 0xeb:'e', 
     0xec:'i', 0xed:'i', 0xee:'i', 0xef:'i', 
     0xf0:'th', 0xf1:'n', 
     0xf2:'o', 0xf3:'o', 0xf4:'o', 0xf5:'o', 0xf6:'o', 0xf8:'o', 
     0xf9:'u', 0xfa:'u', 0xfb:'u', 0xfc:'u', 
     0xfd:'y', 0xfe:'th', 0xff:'y', 
     0xa1:'!', 0xa2:'{cent}', 0xa3:'{pound}', 0xa4:'{currency}', 
     0xa5:'{yen}', 0xa6:'|', 0xa7:'{section}', 0xa8:'{umlaut}', 
     0xa9:'{C}', 0xaa:'{^a}', 0xab:'<<', 0xac:'{not}', 
     0xad:'-', 0xae:'{R}', 0xaf:'_', 0xb0:'{degrees}', 
     0xb1:'{+/-}', 0xb2:'{^2}', 0xb3:'{^3}', 0xb4:"'", 
     0xb5:'{micro}', 0xb6:'{paragraph}', 0xb7:'*', 0xb8:'{cedilla}', 
     0xb9:'{^1}', 0xba:'{^o}', 0xbb:'>>', 
     0xbc:'{1/4}', 0xbd:'{1/2}', 0xbe:'{3/4}', 0xbf:'?', 
     0xd7:'*', 0xf7:'/' 
    } 

    r = '' 
    for i in unicrap: 
     if xlate.has_key(ord(i)): 
      r += xlate[ord(i)] 
     elif ord(i) >= 0x80: 
      pass 
     else: 
      r += i 
    return r 

# This gives an example of how to use latin1_to_ascii(). 
# This creates a string will all the characters in the latin-1 character set 
# then it converts the string to plain 7-bit ASCII. 
if __name__ == '__main__': 
s = unicode('','latin-1') 
for c in range(32,256): 
    if c != 0x7f: 
     s = s + unicode(chr(c),'latin-1') 
print 'INPUT:' 
print s.encode('latin-1') 
print 
print 'OUTPUT:' 
print latin1_to_ascii(s) 
看看這個鏈接[絕密]

這裏是代碼

+0

你的鏈接把我帶到「布蘭妮斯皮爾斯裸體」 – mpen 2010-06-27 21:14:41

+2

@馬克 - 哈,萬歲的永恆鏈接! – 2010-06-28 03:12:44

1

我會做這樣的事情

# coding=utf-8 

def alnum_dot(name, replace={}): 
    import re 

    for k, v in replace.items(): 
     name = name.replace(k, v) 

    return re.sub("[^a-z.]", "", name.strip().lower()) 

print alnum_dot(u"Frédrik Holmström", { 
    u"ö":"o", 
    " ":"." 
}) 

第二個參數是要替換的字符的字典,所有非A-Z和。未被替換的字符將被刪除

1

translate方法允許您刪除字符。您可以使用它來刪除任意字符。

Fullname.translate(None,"'-\"") 

如果要刪除整個類的字符,可能需要使用re模塊。

re.sub('[^a-z0-9 ]', '', Fullname.strip().lower(),) 
3

下面的函數是通用的:

import unicodedata 

def not_combining(char): 
     return unicodedata.category(char) != 'Mn' 

def strip_accents(text, encoding): 
     unicode_text= unicodedata.normalize('NFD', text.decode(encoding)) 
     return filter(not_combining, unicode_text).encode(encoding) 

# in a cp1252 environment 
>>> print strip_accents("déjà", "cp1252") 
deja 
# in a cp1253 environment 
>>> print strip_accents("καλημέρα", "cp1253") 
καλημερα 

很顯然,你應該知道你的字符串的編碼。

5

如果你不怕安裝第三方模塊,那麼看看python port of the Perl module Text::Unidecode(它也是on pypi)。

該模塊只是使用查找表來音譯字符。我瀏覽了代碼,它看起來很簡單。所以我認爲它可以在任何操作系統和任何Python版本(交叉指針)上工作。與您的應用程序捆綁也很容易。

使用此模塊,您不必手動創建查找表(=減少了不完整的風險)。

與unicode標準化技術相比,此模塊的優點是:Unicode標準化不會替換所有字符。一個很好的例子是像「æ」這樣的字符。 Unicode規範化會將其視爲「Letter,lowercase」(Ll)。這意味着使用normalize方法將不會爲您提供替換字符,也不會提供有用的提示。不幸的是,該字符不能用ASCII表示。所以你會得到錯誤。

提到的module在這方面做得比較好。這實際上將用「ae」代替「æ」。這實際上有用並且有意義。

我見過的最令人印象深刻的事情是它更進一步。它甚至取代日本假名字符主要是正確。例如,用「ha」代替「は」。這很好。 雖然現在的版本用「ti」代替「chi」代替了「ち」,但這並不是傻瓜式的。所以你必須小心處理更奇特的角色。該模塊的

用法很簡單::

from unidecode import unidecode 
var_utf8 = "æは".decode("utf8") 
unidecode(var_utf8).encode("ascii") 
>>> "aeha" 

注意,我什麼都沒有做這個模塊直接。只是碰巧我覺得它非常有用。

編輯:我提交的補丁修正了有關日本假名的錯誤。我只修好了我可以馬上發現的那個。我可能錯過了一些。