写入文件时出现UnicodeEncodeError

19 投票
3 回答
20026 浏览
提问于 2025-04-16 22:52

我正在尝试把一些字符串写入一个文件(这些字符串是通过HTML解析器BeautifulSoup给我的)。

我可以用“print”来显示这些字符串,但当我用file.write()的时候,出现了以下错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 6: ordinal not in range(128)

我该怎么处理这个问题呢?

3 个回答

2

你问的问题的答案是“使用codecs”。附上的代码也展示了一些gettext的神奇之处,顺便提一下。http://wiki.wxpython.org/Internationalization

import codecs

import gettext

localedir = './locale'
langid = wx.LANGUAGE_DEFAULT # use OS default; or use LANGUAGE_JAPANESE, etc.
domain = "MyApp"             
mylocale = wx.Locale(langid)
mylocale.AddCatalogLookupPathPrefix(localedir)
mylocale.AddCatalog(domain)

translater = gettext.translation(domain, localedir, 
                                 [mylocale.GetCanonicalName()], fallback = True)
translater.install(unicode = True)

# translater.install() installs the gettext _() translater function into our namespace...

msg = _("A message that gettext will translate, probably putting Unicode in here")

# use codecs.open() to convert Unicode strings to UTF8

Logfile = codecs.open(logfile_name, 'w', encoding='utf-8')

Logfile.write(msg + '\n')

尽管在谷歌上搜索这个问题能找到很多结果,但我发现找到这个简单的解决方案还是挺困难的(其实在Python的Unicode文档里有提到,只是埋得比较深)。

所以……希望对你有帮助……

GaJ

16

这个错误发生在你试图把包含非英语字符的Unicode字符串(也就是Unicode字符编码超过128的字符)传给一个只接受ASCII字节串的地方。Python中的字节串默认使用ASCII编码,而ASCII编码只能处理128个字符(也就是英语字符)。所以,当你尝试转换超过128的Unicode字符时,就会出现错误。

unicode()

unicode(string[, encoding, errors])

这个构造函数的格式是unicode(string[, encoding, errors])。它的所有参数都应该是8位字符串。

第一个参数会根据你指定的编码转换成Unicode;如果你不提供编码参数,默认会使用ASCII编码进行转换,这样大于127的字符就会被当作错误处理。

例如

s = u'La Pe\xf1a' 
print s.encode('latin-1')

或者

write(s.encode('latin-1'))

会使用latin-1编码进行转换。

2

我试过这个,效果很好。

with open(r"C:\rag\sampleoutput.txt", 'w', encoding="utf-8") as f:  

撰写回答