Tôi có đoạn mã sau:Tôi làm cách nào để str.translate hoạt động với chuỗi 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)
Những công trình vĩ đại cho các chuỗi không unicode:
>>> translate_non_alphanumerics('<foo>!')
'_foo__'
Nhưng không cho các chuỗi 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
tôi không thể thực hiện bất kỳ ý nghĩa của đoạn trên "đối tượng Unicode" trong Python 2.6.2 docs cho phương thức str.translate().
Làm cách nào để thực hiện công việc này cho chuỗi Unicode?
đây là [ví dụ xóa dấu chấm câu Unicode khỏi chuỗi bằng phương thức 'unicode.translate()' (http://stackoverflow.com/a/11066687/4279). – jfs
sử dụng tốt hơn 'chuỗi nhập; string.punctuation' thay vì hardcoding 'not_letters_or_digits' trong mã thực. Tôi nhận được rằng ở đây bạn muốn được rõ ràng. –