日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python搜索word关键字_Python根据关键字抓取word相关内容

發布時間:2023/12/10 python 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python搜索word关键字_Python根据关键字抓取word相关内容 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

用python我們可以抓取網頁,表格,JSON這種半結構化的數據,那么word文檔中的內容這種非結構化的數據我們如何抓取呢。

今天我來教大家如何實現python對docx類型的文檔中數據的讀取,并根據關鍵字提取相應的內容,然后入庫。

首先配置docx文檔處理庫

pip install python-docx

下面是詳細的代碼

import pymysql.cursors

import docx

import re

def get_file(path):

'''獲取文件'''

#獲得word文檔

file = docx.Document(path)

#print(file)

return file

def preproccess_file(file):

'''文件預處理'''

#輸出文檔段落數(行數)

paragraph_sum = len(file.paragraphs)

#print(paragraph_sum)

#輸出每一段的內容

para_list = []

for para in file.paragraphs:

print(para.text)

para_list.append(para.text)

#合并字符串

file_text = ''.join(para_list)

print(file_text)

return file_text

def extract_file(keyword, file_text):

'''提取內容'''

#使用正則提取關鍵字后面的數字

result = re.findall('{}([0-9]*)'.format(keyword), file_text)

print(result)

return result

def sql_connection():

'''建立數據連接'''

#使用pymysql指令連接數據庫

connection = pymysql.connect(host = '127.0.0.1', #要連接的數據庫的IP地址

user = 'root', #登錄的賬戶名,如果登錄的是最高權限賬戶則為root

password = '123456', #對應的密碼

db = 'sucomputer_db', #要連接的數據庫

charset = 'utf8mb4', #設置編碼格式

#返回到Python的結果,以什么方式存儲,如Dict.Cursor是以字典的方式存儲

#如果不加這行數據是以元組方式返回

cursorclass = pymysql.cursors.DictCursor

)

return connection

def insert_text_to_sql(connection,search_result,keyword):

'''創建表'''

try:

# 使用cursor()方法獲取操作游標word

with connection.cursor() as cursor:

'''判斷表是否存在,如果不存在創建表'''

sql_show_table = 'SHOW TABLES'

cursor.execute(sql_show_table)

tables = cursor.fetchall()

table_list = []

for table in tables:

for value in table.values():

table_list.append(value)

if 'words' not in table_list:

sql = '''create table words(

name varchar(256) not null,

number int) engine=InnoDB DEFAULT CHARSET=utf8;

'''

cursor.execute(sql)

print('創建表成功')

# 插入數據

# 從數據庫鏈接中得到cursor的數據結構

num = 0;

print('開始插入數據')

for i in search_result:

with connection.cursor() as cursor:

sql = " insert into words(name, price) VALUES (%s, %s)"

cursor.execute(sql,(keyword,i))

# 執行到這一行指令時才是真正改變了數據庫,之前只是緩存在內存中

connection.commit()

num += 1;

print('成功插入{}條數據'.format(num))

print('數據插入完畢!')

except:

# 發生錯誤時回滾

connection.rollback()

finally:

# 關閉連接

connection.close()

def main():

path = '/Users/sfs1100126com/Desktop/word/test.docx'; #文件路徑

keyword = '超算科技' #提取關鍵字

file = get_file(path) #獲取文件內容

file_text = preproccess_file(file) #對文件內容預處理(把文本集中到一個字符串中)

search_result = extract_file(keyword, file_text) #提取內容

connection = sql_connection() #獲取數據連接

insert_text_to_sql(connection,search_result,keyword) #最終結果插入數據庫

if __name__ == '__main__':

main()

總結

以上是生活随笔為你收集整理的python搜索word关键字_Python根据关键字抓取word相关内容的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。