将 UTF-8 转换为 ASCII 的 Python 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4299675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python script to convert from UTF-8 to ASCII
提问by Nicolas
I'm trying to write a script in python to convert utf-8 files into ASCII files:
我正在尝试在 python 中编写一个脚本来将 utf-8 文件转换为 ASCII 文件:
#!/usr/bin/env python
# *-* coding: iso-8859-1 *-*
import sys
import os
filePath = "test.lrc"
fichier = open(filePath, "rb")
contentOfFile = fichier.read()
fichier.close()
fichierTemp = open("tempASCII", "w")
fichierTemp.write(contentOfFile.encode("ASCII", 'ignore'))
fichierTemp.close()
When I run this script I have the following error :
当我运行此脚本时,出现以下错误:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 13: ordinal not in range(128)
UnicodeDecodeError:“ascii”编解码器无法解码位置 13 中的字节 0xef:序号不在范围内(128)
I thought that can ignore error with the ignore parameter in the encode method. But it seems not.
我认为可以使用 encode 方法中的 ignore 参数忽略错误。但似乎不是。
I'm open to other ways to convert.
我对其他转换方式持开放态度。
采纳答案by Utku Zihnioglu
data="UTF-8 DATA"
udata=data.decode("utf-8")
asciidata=udata.encode("ascii","ignore")
回答by Ignacio Vazquez-Abrams
import codecs
...
fichier = codecs.open(filePath, "r", encoding="utf-8")
...
fichierTemp = codecs.open("tempASCII", "w", encoding="ascii", errors="ignore")
fichierTemp.write(contentOfFile)
...
回答by Tobu
UTF-8 is a superset of ASCII. Either your UTF-8 file is ASCII, or it can't be converted without loss.
UTF-8 是 ASCII 的超集。您的 UTF-8 文件要么是 ASCII,要么无法无损转换。

