首页 > 数据库 >python分段读取word文件数据到MySQL数据库和Java读取word数据到MySQL数据库

python分段读取word文件数据到MySQL数据库和Java读取word数据到MySQL数据库

时间:2023-04-14 21:36:51浏览次数:44  
标签:count file word 读取 sql context MySQL pst String

1、python分段读取word文件数据到MySQL数据库

  示例:(注:此示例为读取某个文件夹下的所有文件,并对文件后缀名为doc的文件进行读取,并以文件名称为id完成对该word 内容的插入。)

# 导入os模块
import os
#导入所需库
import pymysql
from docx import Document

# path定义要获取的文件名称的目录
path = "your path"
# os.listdir()方法获取文件夹名字,返回数组
file_name_list = os.listdir(path)
# 转为转为字符串
file_name = file_name_list
# replace替换"["、"]"、" "、"'"
# file_name = file_name.replace("[", "").replace("]", "").replace("'", "").replace(",", "\n").replace(" ", "")
for fileitem in file_name:
    totalname = fileitem.split('.')
    print(totalname[0],end=">>")
    print(totalname[1])
    try:
        # print(fileitem)
        if totalname[1] == 'doc':
            strtext = ""
            # 打开word文档
            document = Document(path+"/"+totalname[0]+".doc")
            # 获取所有段落
            all_paragraphs = document.paragraphs
            # 打印看看all_paragraphs是什么东西
            # print(type(all_paragraphs)) #<class 'list'>,打印后发现是列表
            # 是列表就开始循环读取
            for paragraph in all_paragraphs:
                # 打印每一个段落的文字
                # print(paragraph.text)
                # 循环读取每个段落里的run内容
                for run in paragraph.runs:
                    if run.text != ' ':
                        strtext = strtext + run.text + "</br>"
                        # print(strtext)
            try:
                db = pymysql.connect(host='localhost', port=3306, user='root', passwd='yourpassword', db='your数据库',
                                                 charset='utf8')
                cursor = db.cursor()
                try:
                    sql = "update lawfiles_information_context1 set file_context = '"+strtext+"' where file_title = '"+totalname[0]+"'"
                    cursor.execute(sql)
                    db.commit()
                except Exception as e:
                    # db.rollback()
                    # print(e)                # 关闭光标对象
                    cursor.close()
                    # 关闭数据库连接
                    db.close()
                    # print(run.text, "</br>")  # 打印run内容
            except Exception as es:
                print("files update failed!!")
    except Exception as efile:
        print("file reading failed")

2、Java读取word数据到MySQL数据库

示例(注:以下Java代码同上述Python代码功能相同,均为读取某个文件夹下所有word文件内容并进行逐段读取同时存储至数据库,此处仅为更新数据表某个字段的内容,若要进行插入,可自行更改sql语句)

package testJava;

import com.spire.doc.Document;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;
import util.DbHelper;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author June
 * @date 2023/4/9 13:42
 * 5341
 * 12099
 */
public class Addcontext {
    //更新文件信息
    public static boolean fileupdateInfo(String file_context,String file_title) {
        int count = 0;
        boolean flag = false;
        String sql = "update lawfiles_information_deal_context set file_context = ? where file_title = ?";
        Connection conn = DbHelper.getConnection();
        PreparedStatement pst = null;
        try {
            pst = conn.prepareStatement(sql);
            pst.setString(1,file_context);
            pst.setString(2,file_title);
            count = pst.executeUpdate();
            pst.close();
        } catch (SQLException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } finally {
            if(count>0)
                flag = true;
        }
        return flag;
    }

    //更新文件信息
    public static boolean judgenuLL(String file_context,String file_title) {
        int count = 0;
        boolean flag = false;
        String sql = "update lawfiles_information_deal_context set file_context = ? where file_title = ?";
        Connection conn = DbHelper.getConnection();
        PreparedStatement pst = null;
        try {
            pst = conn.prepareStatement(sql);
            pst.setString(1,file_context);
            pst.setString(2,file_title);
            count = pst.executeUpdate();
            pst.close();
        } catch (SQLException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } finally {
            if(count>0)
                flag = true;
        }
        return flag;
    }

    //更新文件信息
    public static boolean fileupdatepart(String file_context,String file_title) {
        int count = 0;
        boolean flag = false;
        //String sql = "update lawfiles_information_decision set file_context = ? where file_title = ?";
        //String sql = "update lawfiles_information_interpreter set file_context = ? where file_title = ?";
        String sql = "update lawfiles_information_place set file_context = ? where file_title = ?";
        Connection conn = DbHelper.getConnection();
        PreparedStatement pst = null;
        try {
            pst = conn.prepareStatement(sql);
            pst.setString(1,file_context);
            pst.setString(2,file_title);
            count = pst.executeUpdate();
            pst.close();
        } catch (SQLException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } finally {
            if(count>0)
                flag = true;
        }
        return flag;
    }

    public static void main(String[] args) {
        //获取文件路径文件夹下的全部文件列表
        System.out.println("文件有如下:");
        //表示一个文件路径
        File file = new File("D:\\GraduationProject\\program\\coding\\paqu\\laws_regulations\\1crawling\\laws_files3");
        //用数组把文件夹下的文件存起来
        File[] files = file.listFiles();
        System.out.println("共有文件数"+files.length);
        int count = 0;
        int hace = 0;
        //foreach遍历数组
        for (int j=0;j<2000;j++) {
            File file2 = files[j];
            count++;
            hace = files.length - count;
            System.out.println("count_have ==>>"+hace);
            //打印文件列表:只读取名称使用getName();
            //System.out.println("路径:"+file2.getPath());
            //System.out.println("文件夹/文件名:"+file2.getName());
            try{
                //加载Word文档
                Document doc = new Document(file2.getPath());
                String fileName = file2.getName();
                //得到上传文件的扩展名
                String fileExtName = fileName.substring(fileName.lastIndexOf(".")+1);
                if("doc".equals(fileExtName)){
                    //文件名
                    System.out.println(count+">>doc名字:"+file2.getName().substring(0,file2.getName().length()-4));
                    System.out.println(count+">>doc名字:"+file2.getName());
                    System.out.println("doc内容:--------------------------------------------------------------------");
                    String context = "";
                    //遍历文档中的节和段落,获取每个段落的文本
                    for(int i = 0; i < doc.getSections().getCount(); i++) {
                        context = "";
                        try {
                            Section section = doc.getSections().get(i);
                            for(int p=0;p<section.getParagraphs().getCount();p++){
                                context = context + "\n" + section.getParagraphs().get(p).getText();
                            }
                            //System.out.println("context:"+context);
                            //System.out.println(context);
                            fileupdatepart(context,file2.getName().substring(0,file2.getName().length()-4));
                        }catch (Exception e){
                            System.out.println(count+">>read------false"+file2.getName().substring(0,file2.getName().length()-4));
                        }
                    }
                }

            }catch (Exception e){
                System.out.println(count+">>file------false");
            }

        }



    }
}

对比而言:

  (别问,实践证明。。。。python快。。。。。)python读取word文件的速度相比Java读取word文件的速度要快。

标签:count,file,word,读取,sql,context,MySQL,pst,String
From: https://www.cnblogs.com/lx06/p/17319995.html

相关文章

  • mysqlhotcopy
    mysqlhotcopy是一个Perl脚本,最初由TimBunce编写并提供。它使用LOCKTABLES、FLUSHTABLES和cp或scp来快速备份数据库。它是备份数据库或单个表的最快的途径,但它只能运行在数据库目录所在的机器上。mysqlhotcopy只用于备份MyISAM。它运行在Unix和NetWare中。.与mysqldump备份不同,m......
  • 使用 Mybatis 对 mysql 查询时间范围
    需求:1.传入开始时间(startTime)和结束时间(endTime),查询effective_time在区间[startTime,endTime]中的数据。Controller中的时间入参用String表示://查询接口,默认查询今年内的数据。@GetMapping(value="/getData")publicList<Demo>selectDemoData(@Req......
  • 运行mysql容器以及通过命令行访问数据库
    运行mysql容器下面命令将创建一个名为mysql-8.0.31的容器,并将容器中的MySQL根密码设置为root。dockerrun--namemysql-8.0.31-p3306:3306-eMYSQL_ROOT_PASSWORD=root-dmysql:8.0.31访问mysqlmysql-h127.0.0.1-P3306-u<username>-p导入sql文件创建数据......
  • Java接收到MySQL数据库查询出的date类型的数据输出格式不对
    问题查询某条数据,里面有个effective_time字段,数据库里保存的该条数据的effective_time的值是2023-04-13,但是使用postman调用接口,返回的确是2023-04-12T16:00:00.000+00:00,不仅格式不对,而且时间还慢了一天。但是在application.yml中配置数据库连接的时候,确实指定了时区......
  • MySQL学习笔记-索引
    索引索引(index)是帮助MySQL高效获取数据的数据结构(有序)。在数据之外,数据库系统还维护着满足特定查找算法的数据结构,这些数据结构以某种方式引用(指向)数据,这样就可以在这些数据结构上实现高级查找算法,这种数据结构就是索引。无索引的查找:全表扫描(将整张表遍历一遍),性能......
  • MySQL数据库实现主主同步
    前言MySQL主主同步实际上是在主从同步的基础上将从数据库也提升成主数据库,让它们可以互相读写数据库,从数据库变成主数据库;主从相互授权连接,读取对方binlog日志并更新到本地数据库的过程,只要对方数据改变,自己就跟着改变。1.主主同步的优与劣事实上每个技术都有它的优劣势,我们......
  • mysql之审计
    ###################https://blog.csdn.net/weihaodong0557/article/details/113805838  showvariableslike'have%';   //查看hava_openssl mkdir/home/work/mysql_3306/ssl//home/work/mysql_3306/bin/mysql_ssl_rsa_setup--datadir=/home/work/mysql_33......
  • 【MySQL】Navicat Premium连接MySQL错误
    mysql8.0出现的2059-authenticationplugin'caching_sha2_password'-navicat连接异常问题解决1.找到配置文件my.ini将default_authentication_plugin=caching_sha2_password改为default_authentication_plugin=mysql_native_password2.用命令行登陆mysql-uroot-p123......
  • android 读取本地数据库db文件(Android sqlite)
    本文由简悦SimpRead转码,原文地址cloud.tencent.com腾讯云备案控制台开发者社区学习实践活动专区工具TVP文章/答案/技术大牛搜索搜索关闭写文章提问登录/注册全栈程序员站长55.1K篇文章android读取本地数据库db文件(Androidsqlite)转到我的清单专栏首页全栈程序员必看......
  • MySQL(十四)分析查询语句Explain 七千字总结
    分析查询语句:EXPLAIN1概述​ 定位了查询慢的SQL之后,就可以使用EXPLAIN或者DESCRIBE工具做针对性的分析查询。两者使用方法相同,并且分析结果也是相同的。​ MySQL中有专门负责SQL语句优化的优化器模块,主要功能是计算分析系统中收集到的统计信息,为客户端请求的Query提供它最优的......