如何将.txt文件转移至MongoDB?

2024-04-20 01:16:27 发布

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

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

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

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

...TAB...表示有一个tab键,或者一个很大的空格。(对不起,我不知道该怎么形容。)

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

^{pr2}$

我尝试使用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)

老实说,作为一个新手,我不太明白代码的含义。因此,上面的代码不适合我的目的并不奇怪。在

有谁能帮我解决这个问题吗?任何帮助将不胜感激!在


Tags: 文件the代码textfromtxtclientmongodb
1条回答
网友
1楼 · 发布于 2024-04-20 01:16:27

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

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))

相关问题 更多 >