消除 python 中的重音

Eliminate accents in python

我有去除单词重音的功能

def remove_accents(word):
    return ''.join(x for x in unicodedata.normalize('NFKD', word) if x in string.ascii_letters)

但是当我 运行 它显示错误

UnicodeDecodeError: 'ascii' codec can't decode byte 0xf3 in position 3: ordinal not in range(128)

第3位的字符是:ó

如果您输入的是 unicode 字符串,它会起作用:

>>> remove_accents(u"foóbar")
u'foobar'

如果不是,那就不是。我没有收到您描述的错误,而是收到了 TypeError,只有在我尝试通过

将其转换为 unicode 时才会收到 UnicodeDecodeError
>>> remove_accents(unicode("foóbar"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 2: ordinal not in range(128)

如果这是你的问题,即你有 Python 2 str 个对象作为输入,你可以先将其解码为 utf-8 来解决它:

>>> remove_accents("foóbar".decode("utf-8"))
u'foobar'