在数据库中缓存大型非unicode字典?

use*_*003 3 python database dictionary data-dictionary mongodb

我有一个大字典(输出为366MB中的字符串,~383764153行filetextfile),我想存储在数据库中以便快速访问并跳过填充字典所涉及的计算时间.

我的字典由文件名/内容对的字典组成.小子集:

{
    'Reuters/19960916': {
        '54826newsML': '<?xml version="1.0"
encoding="iso-8859-1" ?>\r\n<newsitem itemid="54826" id="root"
date="1996-09-16" xml:lang="en">\r\n<title>USA: RESEARCH ALERT -
Crestar Financial cut.</title>\r\n<headline>RESEARCH ALERT - Crestar
Financial cut.</headline>\r\n<text>\n<p>-- Salomon Brothers analyst
Carole Berger said she cut her rating on Crestar Financial Corp to
hold from buy, at the same time lowering her 1997 earnings per share
view to $5.40 from $5.85.</p>\n<p>-- Crestar said it would buy
Citizens Bancorp in a $774 million stock swap.</p>\n<p>-- Crestar
shares were down 2-1/2 at 58-7/8. Citizens Bancorp soared 14-5/8 to
46-7/8.</p>\n</text>\r\n<copyright>(c) Reuters Limited',
        '55964newsML': '<?xml version="1.0" encoding="iso-8859-1"
?>\r\n<newsitem itemid="55964" id="root" date="1996-09-16"
xml:lang="en">\r\n<title>USA: Nebraska cattle sales thin at
$114/dressed-feedlot.</title>\r\n'
    }
}
Run Code Online (Sandbox Code Playgroud)

我想MongoDB的将是一个不错的选择,但它看起来像它需要两个键和值需要是unicode的,因为我是从抓住的文件名namelist()ZipFile就不能保证是Unicode.

您如何推荐我将此字典序列化到数据库中?

geo*_*org 5

pymongo 不需要字符串为unicode,它实际上发送ascii stings并将unicodes编码为UTF8.从pymongo检索数据时,总是得到unicode.@@ http://api.mongodb.org/python/2.0/tutorial.html#a-note-on-unicode-strings

如果您的输入包含具有高位字节(如ab\xC3cd)的"国际"字节字符串,则需要将这些字符串转换为unicode或将它们编码为UTF-8.这是一个处理任意嵌套dicts的简单递归转换器:

def unicode_all(s):
    if isinstance(s, dict):
        return dict((unicode(k), unicode_all(v)) for k, v in s.items())
    if isinstance(s, list):
        return [unicode_all(v) for v in s]
    return unicode(s)
Run Code Online (Sandbox Code Playgroud)