python - 如何在 MongoDB 字段中存储不同语言(非英语)的数据并检索相同的数据?

标签 python mongodb encoding utf-8 pymongo

我想在 MongoDB 字段中存储非英语(如:孟加拉语、印地语)数据。

This is my approach:-

import pymongo
from pymongo import MongoClient
client = MongoClient()
db = client.testdb

db['testing'].save({'data':'শুভ নববর্ষ'})

我遇到了异常。 异常值:第 5 行文件/test/views.py 中的非 ASCII 字符“\xe0”,但未声明编码;见 http://www.python.org/peps/pep-0263.html详情(views.py,第 5 行)

之后我尝试过这样的:-

from bson import BSON
bson_string = BSON.encode({'data':'শুভ নববর্ষ'})
db['testing'].save({'data':'শুভ নববর্ষ'})

这次我也遇到了同样的错误。

编辑:- 基本上我无法在 IDLE

print 'শুভ নববর্ষ'
>>>print 'শুভ নববর্ষ'
Unsupported characters in input

第一次编辑 :-

我在 views.py 中添加了 # -*- coding: utf-8 -*- 然后能够以某种方式存储数据。 但是这个对象结构和mongodb中的普通数据结构是不一样的。 喜欢:-

> db['testing'].find()
{ষ" } : ObjectId("52d65a50012bad0b23c13a65"), "data" : "শà§à¦­ নববরà


I have added another record.
>db['testing'].save({'data':'kousik chowdhury'})

Now the collection is looking funny.
> db['testing'].find()                                                           ষ" }
{ "_id" : ObjectId("52d65e6a012bad0a39a2685b"), "data" : "kousik chowdhury" }¦°à§

> db['testing'].find().length()
2

数据检索:-

** I am using PuTTY as a editor. 

>>> a = db['testing'].find()[0]
>>> a
{u'_id': ObjectId('52d65a50012bad0b23c13a65'), u'data': u'\u09b6\u09c1\u09ad\u09a8\u09ac\u09ac\u09b0\u09cd\u09b7'}
>>> mydata = a['data']
>>>mydata
u'\u09b6\u09c1\u09ad \u09a8\u09ac\u09ac\u09b0\u09cd\u09b7'
>>>mydata.encode('utf-8')
'\xe0\xa6\xb6\xe0\xa7\x81\xe0\xa6\xad \xe0\xa6\xa8\xe0\xa6\xac\xe0\xa6\xac\xe0\xa6\xb0\xe0\xa7\x8d\xe0\xa6\xb7'

是否有任何标准流程,以便我可以将其以正确的格式存储在 mongodb 中并取回数据?

最佳答案

你有线路吗:

# -*- coding: <encoding name> -*-

在文件的开头? 例如:

# -*- coding: utf-8 -*-

第 2 部分:

  • 保存数据使用 unicode 前缀 (u'')

  • 假设你想做 a['data'].encode('utf-8') 它工作正常 - 只是

    打印一个['data'].encode('utf-8')

提示:用某个值覆盖基本类型永远没有充分的理由...(我的意思是 str='')

关于python - 如何在 MongoDB 字段中存储不同语言(非英语)的数据并检索相同的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21085939/

相关文章:

node.js - 无法将随机字符串分配给 _id 字段。

encoding - MPEG-TS 分段 HTTP 直播

python - 使用 CEFPython 为 Chromium 嵌入式框架定义自定义方案处理程序

python - 查找 Python 和 MySQL 脚本中的性能瓶颈

python - 解析 python asciitree 输出并打印 'labelled bracket notation'

encryption - 如何从 RSA 公钥获取私钥?

python - 对列表列表进行编码的优雅方式

python - py2exe:减少库存档的大小

node.js - 使用nodeJS Strapi连接mLab mongoDB数据库

node.js - 你怎么知道数据已经新添加到你的 MongoDB 中了