将 UTF-8 转换为 ASCII 的 Python 脚本 [英] Python script to convert from UTF-8 to ASCII

查看:59
本文介绍了将 UTF-8 转换为 ASCII 的 Python 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用 python 编写一个脚本来将 utf-8 文件转换为 ASCII 文件:

I'm trying to write a script in python to convert utf-8 files into ASCII files:

#!/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' 编解码器无法解码位置 13 中的字节 0xef:序号不在范围内(128)

UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 13: ordinal not in range(128)

我认为可以通过 encode 方法中的 ignore 参数忽略错误.但好像不是.

I thought that can ignore error with the ignore parameter in the encode method. But it seems not.

我愿意接受其他转换方式.

I'm open to other ways to convert.

推荐答案

data="UTF-8 DATA"
udata=data.decode("utf-8")
asciidata=udata.encode("ascii","ignore")

这篇关于将 UTF-8 转换为 ASCII 的 Python 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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