我需要替换非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 ½
发布于 2016-03-23 00:40:10
您将本地变量unicode读入为字节,然后将data
视为已经是data
对象。
更改此设置:
with open(file_name, "r") as myfile:
data = myfile.read()
要这样做:
import io
with io.open(file_name, encoding="utf8") as myfile:
data = myfile.read()
发布于 2016-03-23 00:42:01
我认为您的初始字符串没有正确编码为unicode。
您正在尝试的内容工作正常:
>>> st=u"¼½¾"
>>> print st.replace(u"½", u"1/2")
¼1/2¾
但目标首先需要是unicode。
https://stackoverflow.com/questions/36159806
复制相似问题