gpt4 book ai didi

python - 将txt文件的全文存储到mongodb中

转载 作者:行者123 更新时间:2023-11-30 21:50:30 31 4
gpt4 key购买 nike

我创建了一个 python 脚本,可以自动执行将 PDF 转换为 txt 文件的工作流程。我希望能够在 MongoDB 中存储和查询这些文件。我需要将 .txt 文件转换为 JSON/BSON 吗?我应该使用像 PyMongo 这样的程序吗?

我只是不确定这样一个项目的步骤是什么,更不用说有助于实现此目的的工具了。

我看过这篇文章:How can one add text files in Mongodb? ,这让我觉得我需要将文件转换为 JSON 文件,并可能集成 GridFS?

最佳答案

如果您使用驱动程序,则不需要对其进行 JSON/BSON 编码。如果您使用 MongoDB shell,则在粘贴内容时需要担心它。

您可能想要使用Python MongoDB driver :

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('test_file_name.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": "test_file_name.txt", "contents" : text }
# insert the contents into the "file" collection
collection.insert(text_file_doc)

(未经测试的代码)

如果您确保文件名是唯一的,您可以设置文档的 _id 属性并检索它,如下所示:

text_file_doc = collection.find_one({"_id": "test_file_name.txt"})

或者,您可以确保如上所示的 file_name 属性已建立索引并执行以下操作:

text_file_doc = collection.find_one({"file_name": "test_file_name.txt"})

您的另一个选择是使用 GridFS,尽管通常不建议将其用于小文件。

有一个启动器here适用于 Python 和 GridFS。

关于python - 将txt文件的全文存储到mongodb中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16307552/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com