Python script to convert from UTF-8 to ASCII(将 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 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:将 UTF-8 转换为 ASCII 的 Python 脚本
基础教程推荐
猜你喜欢
- 尝试制作WhatsApp机器人 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
