【问题标题】:how to replace non ascii char in python如何在python中替换非ascii char
【发布时间】:2016-07-09 15:50:18
【问题描述】:

我需要在 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 ½

【问题讨论】:

  • @TusharGupta 这删除了字符 ...
  • 如果可以去掉,可以用它来代替。试试看;)
  • 我确实尝试了很多,这就是我问的原因,我现在没有想法
  • 能否提供data的内容(或一小部分)?

标签: python python-2.x


【解决方案1】:

看起来您想将其读取为 unicode,但 pyhton 将其读取为字符串。试试这个,问题看起来和你的UnicodeDecodeError类似

https://stackoverflow.com/a/18649608/5504999

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

【讨论】:

  • 我得到:UnicodeEncodeError: 'ascii' codec can't encode character u'\uf057' in position 383: ordinal not in range(128)
  • 您是否尝试使用 u.decode('utf-8') 读取 replace() 中的第一个参数?
  • 看@wim的回答。
  • 我试过:使用 codecs.open(HTML_PATH + file_name, "r", "utf8") as myfile: data = myfile.read() data = data.replace(u"½", u "1/2") 我得到: SyntaxError: Non-ASCII character '\xc2' in file
  • 试试我的答案,即在文件顶部添加#coding: utf-8。它允许程序读取非ASCII字符。
【解决方案2】:

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

【讨论】:

  • 仍然得到:SyntaxError: Non-ASCII character '\xc2' in file
【解决方案3】:

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

你正在尝试的工作正常:

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

但目标必须是 unicode 才能开始。

【讨论】:

  • 这正是我的代码所做的:data.replace(u"½", u"1/2") 但不起作用
  • data 不是 unicode 字符串。这就是为什么它不适合你。看看wim的回答。
  • 我试过:使用 codecs.open(HTML_PATH + file_name, "r", "utf8") as myfile: data = myfile.read() data = data.replace(u"½", u "1/2") 我得到: SyntaxError: Non-ASCII character '\xc2' in file
猜你喜欢
  • 2011-02-24
  • 1970-01-01
  • 1970-01-01
  • 2017-04-13
  • 2017-12-10
  • 2021-04-10
  • 2016-04-06
  • 2015-08-14
  • 1970-01-01
相关资源
最近更新 更多