如何使用Python将文件的格式从Unicode转换为ASCII? [英] How do I convert a file's format from Unicode to ASCII using Python?

查看:170
本文介绍了如何使用Python将文件的格式从Unicode转换为ASCII?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以Unicode格式输出文件的第三方工具。但是,我更喜欢ASCII。该工具没有更改文件格式的设置。

I use a 3rd party tool that outputs a file in Unicode format. However, I prefer it to be in ASCII. The tool does not have settings to change the file format.

使用Python转换整个文件格式的最佳方法是什么?

What is the best way to convert the entire file format using Python?

推荐答案

只需使用 unicode 函数即可轻松转换文件,但您将遇到问题Unicode字符无ASCII ASCII等价物。

You can convert the file easily enough just using the unicode function, but you'll run into problems with Unicode characters without a straight ASCII equivalent.

这个博客建议 unicodedata 模块,它似乎在大致转换字符而没有直接相应的ASCII值,例如

This blog recommends the unicodedata module, which seems to take care of roughly converting characters without direct corresponding ASCII values, e.g.

>>> title = u"Klüft skräms inför på fédéral électoral große"

通常转换为

Klft skrms infr p fdral lectoral groe

这是非常错误的。然而,使用 unicodedata 模块,结果可能更接近原始文本:

which is pretty wrong. However, using the unicodedata module, the result can be much closer to the original text:

>>> import unicodedata
>>> unicodedata.normalize('NFKD', title).encode('ascii','ignore')
'Kluft skrams infor pa federal electoral groe'

这篇关于如何使用Python将文件的格式从Unicode转换为ASCII?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆