【发布时间】:2014-07-19 13:25:27
【问题描述】:
我正在从 Internet 检索数据,我希望它能够将其转换为 ASCII。但我无法修复它。 (Python 2.7)
当我在得到的字符串上使用 decode('utf-8') 时,例如 Yalçınkaya。然而,我希望将其转换为 Yalcinkaya。原始数据是 Yalçınkaya。
谁能帮帮我?
谢谢。
编辑:我已尝试将此问题标记为重复 (What is the best way to remove accents in a Python unicode string?) 的用户提出的建议,但这并没有解决我的问题。
那篇文章主要谈论删除特殊字符,但这并没有解决我将土耳其字符 (Yalçınkaya) 替换为它们的 ascii 字符 (Yalcinkaya) 的问题。
# Printing the raw string in Python results in "Yalçınkaya".
# When applying unicode to utf8 the string changes to 'Yalçınkaya'.
# HTMLParser is used to revert special characters such as commas
# FKD normalize is used, which converts the string to 'Yalçınkaya'.
# Applying ASCII encoding results in 'Yalcnkaya', missing the original turkish 'i' which is not what I wanted.
name = unicodedata.normalize('NFKD', unicode(name, 'utf8'))
name = HTMLParser.HTMLParser().unescape(name)
name = unicodedata.normalize('NFKD', u'%s' %name).encode('ascii', 'ignore')
【问题讨论】:
-
编辑:我已经尝试了将这个问题标记为重复的用户提出的建议(在 python unicode 字符串中删除重音的最佳方法是什么?)但这并没有解决我的问题问题。
-
我重新打开了这个问题,也许您可以确切说明为什么这不能解决您的问题,以便您获得合适的建议...
-
感谢您的编辑。不过还有一件事:您能否提供一个short, self-contained, correct example 来演示您的问题——以便我们能够重现该问题?
-
您是否尝试过该问题的已接受答案中提到的
unidecode库?对我来说,它会将'Yalçınkaya'变成'Yalcinkaya'。 -
你确实是对的。不知道我是怎么错过的,但它有效!非常感谢。 (我怎样才能接受你的回答)?)
标签: python ascii decode encode