【问题标题】:Encoding issue inserting into MongoDB with Python使用 Python 插入 MongoDB 的编码问题
【发布时间】:2012-01-26 00:12:10
【问题描述】:

我有一个字典列表data_dump,其中包含以下字典:

d = {"ids": s_id, "subject": subject}

我正在按照教程尝试进行批量插入:

connection = Connection(host,port)
db = connection['clusters']
posts = db.posts
posts.insert(data_dump)

失败并出现以下错误:

 File "/usr/local/lib/python2.7/dist-packages/pymongo/collection.py", line 312, in insert
continue_on_error, self.__uuid_subtype), safe)
bson.errors.InvalidStringData: strings in documents must be valid UTF-8

请指教。 谢谢

【问题讨论】:

  • 异常很明显。 data_dump 中的某些字符串不是有效的 utf8。 data_dump 是从哪里来的?
  • 尝试使用codecs.open函数读取文件。所以open("file.txt", "r") 会变成import codecs; codecs.open("file.txt", "r", "utf-8")
  • @MikeSteder 我如何确保......对此感到抱歉。我只是将它们读为 f = open(filename,"r") .. 有没有办法强制这样做??

标签: python mongodb unicode pymongo


【解决方案1】:

已解决: 好吧..强制编码 1)剥离符号字符串等 接着 2) 通过 raw.decode('ascii') 将 ascii 转换为 utf-8,然后 decoded_string.encode('utf8') 谢谢大家.. :)

【讨论】:

    【解决方案2】:

    我不能失去非 utf-8 字符。所以我选择将字符串转换为二进制。

    按照你的例子,

    >>> print subject
    u'Math'
    >>> d = {"ids": s_id, "subject": bson.Binary(str(subject))} # convert subject from unicode to Binary
    

    您无法运行全文搜索,这是 Mongo 的最新功能,但它适用于其他所有功能。

    【讨论】:

      猜你喜欢
      • 2013-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-03
      • 2020-01-31
      • 1970-01-01
      • 2021-08-22
      • 2020-01-04
      相关资源
      最近更新 更多