如何替换 python 中的非 ascii 字符

how to replace non ascii char in python

我需要替换 Python 中的 ¾ 等非 ASCII 字符,但我得到

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 ½

看起来你想将它作为 unicode 读取,但 pyhton 将它作为字符串读取。试试这个,问题看起来与您的 UnicodeDecodeError

相似

尝试在文件顶部添加 #coding: utf-8。这将允许使用非 ASCII 字符。

您正在将局部变量 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()

我认为您的初始字符串未正确编码为 un​​icode。

您正在尝试的工作正常:

>>> st=u"¼½¾"
>>> print st.replace(u"½", u"1/2")
¼1/2¾

但目标必须是 unicode 开头。