如何从 Python 中的字符串中删除重音符号

使用 unidecode 包从字符串中删除重音符号,例如 str_without_accents = unidecode(str_with_accents)。 unidecode() 函数将通过将字符替换为可以安全编码为 ASCII 的字符来删除字符串中的所有重音符号。

我们应该做的第一件事是安装 unidecode 包。

$ pip install Unidecode

现在我们可以导入并使用 unidecode 功能。

from unidecode import unidecode

str_with_accents = 'ÂéüÒÑ'

str_without_accents = unidecode(str_with_accents)

print(str_without_accents)  # 👉️ 'AeuON'

unidecode 函数接受一个可能包含非 ASCII 字符的字符串,并返回一个可以安全地编码为 ASCII 的字符串。

如果我们的字符串包含 unidecode 无法转换为 ASCII 兼容字符的字符,该函数将用空字符串替换它们。

from unidecode import unidecode

str_with_accents = 'ÂéüÒÑ\ue123'

str_without_accents = unidecode(str_with_accents)

print(str_without_accents)  # 👉️ 'AeuON'

请注意 ,\ue123 字符无法转换为 ASCII 兼容字符并从字符串中删除。

如果我们想在 unidecode 函数遇到无法转换为 ASCII 兼容字符的字符时引发错误,请将 errors 关键字参数设置为 strict

from unidecode import unidecode

str_with_accents = 'ÂéüÒÑ\ue123'

# ⛔️ unidecode.UnidecodeError: no replacement found for character '\ue123' in position 5
str_without_accents = unidecode(str_with_accents, errors='strict')

unidecode 函数找不到 \ue123 字符的替代品,因此它引发了一个错误。

unidecode 包公开了一个 UnidecodeError 对象,它使我们能够访问无法翻译的字符的索引。

from unidecode import unidecode, UnidecodeError

str_with_accents = 'ÂéüÒÑ\ue123'

# ⛔️ unidecode.UnidecodeError: no replacement found for character '\ue123' in position 5
try:
    str_without_accents = unidecode(str_with_accents, errors='strict')
except UnidecodeError as e:
    print(e.index)  # 👉️ 5

索引 5 处的字符引发了错误。

我们还可以将 errors 关键字参数设置为 replace 以替换无法用另一个字符串翻译的字符。

from unidecode import unidecode

str_with_accents = 'ÂéüÒÑ\ue123'

str_without_accents = unidecode(
    str_with_accents, errors='replace', replace_str='?'
)
print(str_without_accents)  # 👉️ 'AeuON?'

replace_str 关键字参数用于指定替换字符串。

如果要保留无法转换为 ASCII 兼容字符的字符,可以使用 preserve 关键字参数。

from unidecode import unidecode

str_with_accents = 'ÂéüÒÑ\ue123'

str_without_accents = unidecode(
    str_with_accents,
    errors='preserve',
)
print(str_without_accents)  # 👉️ 'AeuON'

但是,如果将 errors 设置为 preserve ,则 unidecode 函数不会生成 ASCII 兼容的字符串。