Ho il seguente codice:Come posso ottenere che str.translate funzioni con le stringhe Unicode?
import string
def translate_non_alphanumerics(to_translate, translate_to='_'):
not_letters_or_digits = u'!"#%\'()*+,-./:;<=>[email protected][\]^_`{|}~'
translate_table = string.maketrans(not_letters_or_digits,
translate_to
*len(not_letters_or_digits))
return to_translate.translate(translate_table)
Quali grandi opere per le stringhe non Unicode:
>>> translate_non_alphanumerics('<foo>!')
'_foo__'
Ma non riesce per le stringhe Unicode:
>>> translate_non_alphanumerics(u'<foo>!')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in translate_non_alphanumerics
TypeError: character mapping must return integer, None or unicode
non posso fare qualsiasi senso del paragrafo su "Oggetti Unicode" nel Python 2.6.2 docs per il metodo str.translate().
Come faccio a funzionare per le stringhe Unicode?
ecco un [esempio che rimuove la punteggiatura Unicode da una stringa usando il metodo 'unicode.translate()' (http://stackoverflow.com/a/11066687/4279). – jfs
usare meglio 'stringa di importazione; string.punctuation' invece di hardcoding 'not_letters_or_digits' in codice reale. Capisco che qui preferiresti essere esplicito. –