写入文件时出现Unicode编码错误

24 浏览
0 Comments

写入文件时出现Unicode编码错误

这个问题已经有了答案:

UnicodeEncodeError:\'ascii\'编解码器无法在第20个字符位置编码字符u\'\\xa0\':序号不在范围内(128)

我正在尝试将一些字符串写入文件(这些字符串已由HTML解析器BeautifulSoup提供)。

我可以使用“print”来显示它们,但当我使用file.write()时,我会收到以下错误:

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

我该如何解析这个错误?

admin 更改状态以发布 2023年5月21日
0
0 Comments

回答您的问题是:“使用编解码器”。附加的代码还展示了一些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')

尽管在Google上有很多关于这个问题的搜索结果,但我发现很难找到这个简单的解决方案(实际上在Python Unicode文档中,但是它被掩盖了)。

所以...希望对您有帮助...

GaJ

0