Skip to main content
 首页 » 编程设计

python之如何在 python 中替换非 ascii 字符

2025年05月04日9lhb25

我需要替换非 ASCII 字符,例如 ¾在 Python 中,但我得到了

SyntaxError: Non-ASCII character '\xc2' in file test.py but no encoding declared; see http://www.python.org/peps/pep-0263.html for details` 

按照说明操作后 on the webpage , 我得到

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

这是我的代码:

data = data.replace(u"½", u"1/2") 
data = re.sub(u"¾", u"3/4", data, flags=re.DOTALL) 

我的代码需要更改什么?


我的文件是:

#!/usr/bin/python 
 
with codecs.open("file.txt", "r", "utf8") as myfile: 
    data = myfile.read() 
 
data = data.replace(u"½", u"1/2") 

file.txt 是:

hello world ½ 

请您参考如下方法:

您正在将局部变量 data 作为字节读入,但随后将 data 视为它已经是一个 unicode 对象。

改变这个:

with open(file_name, "r") as myfile: 
    data = myfile.read() 

对此:

import io 
 
with io.open(file_name, encoding="utf8") as myfile: 
    data = myfile.read()