如何替换带重音的字符?

25

我的输出看起来像'àéêöhello!'。我需要将输出更改为'aeeohello',只需将字符à替换为a即可。


3个回答

49
请使用以下代码:
import unicodedata

def strip_accents(text):
    try:
        text = unicode(text, 'utf-8')
    except NameError: # unicode is a default on python 3 
        pass

    text = unicodedata.normalize('NFD', text)\
           .encode('ascii', 'ignore')\
           .decode("utf-8")

    return str(text)

s = strip_accents('àéêöhello')

print s

1
完美运行。谢谢。 - Guillaume M
2
并非所有字母都适用(仅举几个例子,如Đ、ı、ł)。 - Fejs
为什么要使用str(text)normalize似乎会返回一个字符串(Python 3.9)。 - Safwan Samsudeen
7
名称错误:未定义unicode。Python 3.8。 意思是代码中使用了unicode这个名称,但是在运行时却找不到该名称的定义。 - TomSawyer
没有加上try块的话(text = unicode(text, 'utf-8'))会出错。感谢提供代码。 - erfelipe

13
import unidecode

somestring = "àéêöhello"

#convert plain text to utf-8
u = unicode(somestring, "utf-8")
#convert utf-8 to normal text
print unidecode.unidecode(u)

输出:

aeeohello

6

Alpesh Valaki答案是最好的,但我需要做一些调整才能使其正常工作:

# I changed the import
from unidecode import unidecode

somestring = "àéêöhello"

#convert plain text to utf-8
# replaced unicode by unidecode
u = unidecode(somestring, "utf-8")

#convert utf-8 to normal text
print(unidecode(u))

这对我很有用,尝试将像'Đà Nẵng'这样的东西转换为'Da Nang' - 谢谢! - g0h

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接