迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

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

作者:迹忆客 最近更新:2023/02/03 浏览次数:

使用 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.UnidecodeError: no replacement found for character

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 兼容的字符串。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便