【2024Python教程】-MongoDB数据库连接

MongoDB数据库连接实战

 MongoDB数据库连接

  • 首先,通过以下代码连接到本地的MongoDB:
client = MongoClient('mongodb://localhost:27017/')
  • 然后,创建或切换到名为pdf_contents的数据库:
db = client['pdf_contents']
  • pdf_contents数据库中,创建或切换到名为contents的集合(相当于关系数据库中的表):
collection = db['contents']
  • 在遍历PDF文件的循环中,通过以下代码将每个PDF文件的信息插入到contents集合中:
data = {
    "filename": filename,
    "text": text,
    "category": category
}
collection.insert_one(data)

这里data是一个Python字典,包含了PDF文件名、文本内容和分类信息。collection.insert_one(data)将这个字典作为一个文档插入到contents集合中。

  • 每插入一个文档,就打印一行信息,表示该PDF文件已经处理并存储到MongoDB中。

所以,这段代码的作用是:遍历指定目录下的所有PDF文件,提取每个PDF文件的文本内容,对文本内容进行简单分类,然后将PDF文件名、文本内容和分类信息作为一个文档存储到MongoDB的pdf_contents数据库的contents集合中。


MongoDB实战

 举个例子,我们希望把很多份技术文档(PDF格式)转为TXT,并将文章内容,文章标题存到

MongoDB。

首先安装相关的库:

pip install PyPDF2  
pip install pymongo
pip install sys
pip install io

import PyPDF2  # PyPDF2库
from pymongo import MongoClient  # MongoDB Python驱动

import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')


# 连接到MongoDB数据库
client = MongoClient('mongodb://localhost:27017/')
db = client['pdf_contents']
collection = db['contents']

# 定义一个函数来提取PDF文本内容
def extract_pdf_text(pdf_path):
    with open(pdf_path, 'rb') as pdf_file:
        pdf_reader = PyPDF2.PdfReader(pdf_file)
        text = ""
        for page_num in range(len(pdf_reader.pages)):
            page = pdf_reader.pages[page_num]
            text += page.extract_text()
    return text

# 定义一个函数来对文本进行分类
def categorize_text(text):
    # 这里可以添加自定义的分类逻辑
    # 例如,根据关键词或机器学习模型对文本进行分类
    # 为了简单起见,我们假设只有两个类别:"技术"和"非技术"
    if "code" in text.lower() or "programming" in text.lower():
        category = "技术"
    else:
        category = "非技术"
    return category

# 遍历指定目录下的所有PDF文件
import os
dir_path = "C:/pdf" #只需要在这里替换你的pdf文件夹pdf path
for filename in os.listdir(dir_path):
    if filename.endswith(".pdf"):
        pdf_path = os.path.join(dir_path, filename)
        text = extract_pdf_text(pdf_path)
        category = categorize_text(text)
        data = {
            "filename": filename,
            "text": text,
            "category": category
        }
        collection.insert_one(data)
        print(f"文件 {filename} 已处理并存储到MongoDB")

详细讲讲这里的MongoDB的数据连接

  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值