win32print结果的字符串编码

2024-10-04 11:30:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个非文本字符串,它是通过编程从联机打印文档的标题中获取的。在

当我试图将其提交到MongoDB时,我得到:

bson.errors.InvalidStringData: strings in documents must be valid UTF-8: 'wxPython: Windows Styles and Events Hunter \xab The Mouse Vs. The Python'

字符串检索代码:

^{pr2}$

Tags: the字符串in文档文本标题mongodb编程
2条回答

编码的默认模式是'strict',这将抛出一个错误。在

>>> s = u"wxPython: Windows Styles and Events Hunter « The Mouse Vs. The Python"
>>> s.encode('ascii')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xab' in position 43: ordinal not in range(128)

如果您的数据库只接受ASCII,那么您别无选择,只能进行有损编码。在'ignore'模式下,将跳过所有无法编码的字节:

^{pr2}$

'replace'模式下,它们被替换为?字符:

 >>> s.encode('ascii', 'replace')
'wxPython: Windows Styles and Events Hunter ? The Mouse Vs. The Python'

最后,还有{}:

>>> s.encode('ascii', 'xmlcharrefreplace')
'wxPython: Windows Styles and Events Hunter &#171; The Mouse Vs. The Python'

从你在其他答案中的评论,我可以看出你得到的错误是:

bson.errors.InvalidStringData: strings in documents must be valid UTF-8: 'wxPython: Windows Styles and Events Hunter \xab The Mouse Vs. The Python'

由于«被编码为\xab,这意味着该字符串可能编码在iso-8995-1、iso-8995-15、windows-1252/latin-1中。这可能与计算机的区域设置有关。在

您只需在传递给MongoDB之前对其进行解码,MongoDB支持Unicode字符串(正如您所断言的,它不限于ASCII):

^{pr2}$

现在可以将document传递给Python MongoDB驱动程序。在

要使代码可移植,可以使用编解码器别名mbcs(代替“拉丁语-1”)。mbcs会自动转换为配置的Windows区域设置(感谢@roeland)

相关问题 更多 >