如何从 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 兼容的字符串。
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。