如何将.txt转移到MongoDB?

时间:2018-04-10 05:41:31

标签: python mongodb

我想问一下如何使用python将.txt文件转换为MongoDB。

.txt文件很大(大约800M),但有一个简单的数据结构:

title1...TAB...text1text1text1text1text1text1\n
title2...TAB...text2text2text2text2text2text2\n
title3...TAB...text3text3text3text3text3text3\n

...TAB...表示有一个Tab键或一个大空格。 (对不起,我不知道如何描述它。)

所需的MongoDB格式应如下所示:

{ 
“title”: title1,
“description”: text1text1text1text1text1text1\n,
“extra”: EMPTY
}
... and so on.

我尝试使用storing full text from txt file into mongodb

中的代码
from pymongo import MongoClient

client = MongoClient()
db = client.test_database  # use a database called "test_database"
collection = db.files   # and inside that DB, a collection called "files"

f = open('F:\\ttt.txt')  # open a file
text = f.read()    # read the entire contents, should be UTF-8 text

# build a document to be inserted
text_file_doc = {"file_name": "F:\\ttt.txt", "contents" : text }
# insert the contents into the "file" collection
collection.insert(text_file_doc)

老实说,作为一个新手,我不太清楚代码的含义。因此,上述代码对我的目的不起作用并不奇怪。

有人可以帮我解决这个问题吗?任何帮助将非常感谢!

1 个答案:

答案 0 :(得分:1)

归结为输入文件的格式化方式。 如果它始终遵循您概述的格式,即标题部分中没有制表符/空格字符,并且“额外”字段将始终为空,您可以选择某事。像这样:

import json

# your mongo stuff goes here

file_content = []
with open("ttt.txt") as f:
    for line in f:
        # assuming tabs and not multiple space characters
        title, desc = line.strip().split("\t", maxsplit=1) 
        file_content.append({"title": title, "description": desc, "extra": None})

collection.insert(json.dumps(file_content))