Python實現(xiàn)文件查詢關(guān)鍵字功能的示例詳解
咱們可以想象一個這樣的場景,你這邊有大量的文件,現(xiàn)在我需要查找一個 序列號:xxxxxx,我想知道這個 序列號:xxxxxx 在哪個文件中。
在沒有使用代碼腳本的情況下,你可能需要一個文件一個文件打開,然后按 CTRL+F 來進行搜索查詢。
那既然我們會使用 python,何不自己寫一個呢?本文將實現(xiàn)這樣一個工具,且源碼全在文章中,只需要復(fù)制粘貼即可使用。
思路
主要思路就是通過打開文件夾,獲取文件,一個個遍歷查找關(guān)鍵字,流程圖如下:

流程圖
怎么樣,思路非常簡單,所以其實實現(xiàn)也不難。
本文將支持少部分文件類型,更多類型需要讀者自己實現(xiàn):
- txt
- docx
- csv
- xlsx
- pptx
讀取txt
安裝庫
pip install chardet
代碼
import chardet
def detect_encoding(file_path):
raw_data = None
with open(file_path, 'rb') as f:
for line in f:
raw_data = line
break
if raw_data is None:
raw_data = f.read()
result = chardet.detect(raw_data)
return result['encoding']
def read_txt(file_path, keywords=''):
is_in = False
encoding = detect_encoding(file_path)
with open(file_path, 'r', encoding=encoding) as f:
for line in f:
if line.find(keywords) != -1:
is_in = True
break
return is_in我們使用了 chardet 庫來判斷 txt 的編碼,以應(yīng)對不同編碼的讀取方式。
讀取docx
安裝庫
pip install python-docx
代碼
from docx import Document
def read_docx(file_path, keywords=''):
doc = Document(file_path)
is_in = False
for para in doc.paragraphs:
if para.text.find(keywords) != -1:
is_in = True
break
return is_in讀取csv
代碼
import csv
def read_csv(file_path, keywords=''):
is_in = False
encoding = detect_encoding(file_path)
with open(file_path, mode='r', encoding=encoding) as f:
reader = csv.reader(f)
for row in reader:
row_text = ''.join([str(v) for v in row])
if row_text.find(keywords) != -1:
is_in = True
break
return is_in讀取xlsx
安裝庫
pip install openpyxl
代碼
from openpyxl import load_workbook
def read_xlsx(file_path, keywords=''):
wb = load_workbook(file_path)
sheet_names = wb.sheetnames
is_in = False
for sheet_name in sheet_names:
sheet = wb[sheet_name]
for row in sheet.iter_rows(values_only=True):
row_text = ''.join([str(v) for v in row])
if row_text.find(keywords) != -1:
is_in = True
break
wb.close()
return is_in讀取pptx
安裝庫
pip install python-pptx
代碼
from pptx import Presentation
def read_ppt(ppt_file, keywords=''):
prs = Presentation(ppt_file)
is_in = False
for slide in prs.slides:
for shape in slide.shapes:
if shape.has_text_frame:
text_frame = shape.text_frame
for paragraph in text_frame.paragraphs:
for run in paragraph.runs:
if run.text.find(keywords) != -1:
is_in = True
break
return is_in文件夾遞歸
為了防止文件夾嵌套導(dǎo)致的問題,我們還有一個文件夾遞歸的操作。
代碼
from pathlib import Path
def list_files_recursive(directory):
file_paths = []
for path in Path(directory).rglob('*'):
if path.is_file():
file_paths.append(str(path))
return file_paths完整代碼
# -*- coding: utf-8 -*-
from pptx import Presentation
import chardet
from docx import Document
import csv
from openpyxl import load_workbook
from pathlib import Path
def detect_encoding(file_path):
raw_data = None
with open(file_path, 'rb') as f:
for line in f:
raw_data = line
break
if raw_data is None:
raw_data = f.read()
result = chardet.detect(raw_data)
return result['encoding']
def read_txt(file_path, keywords=''):
is_in = False
encoding = detect_encoding(file_path)
with open(file_path, 'r', encoding=encoding) as f:
for line in f:
if line.find(keywords) != -1:
is_in = True
break
return is_in
def read_docx(file_path, keywords=''):
doc = Document(file_path)
is_in = False
for para in doc.paragraphs:
if para.text.find(keywords) != -1:
is_in = True
break
return is_in
def read_csv(file_path, keywords=''):
is_in = False
encoding = detect_encoding(file_path)
with open(file_path, mode='r', encoding=encoding) as f:
reader = csv.reader(f)
for row in reader:
row_text = ''.join([str(v) for v in row])
if row_text.find(keywords) != -1:
is_in = True
break
return is_in
def read_xlsx(file_path, keywords=''):
wb = load_workbook(file_path)
sheet_names = wb.sheetnames
is_in = False
for sheet_name in sheet_names:
sheet = wb[sheet_name]
for row in sheet.iter_rows(values_only=True):
row_text = ''.join([str(v) for v in row])
if row_text.find(keywords) != -1:
is_in = True
break
wb.close()
return is_in
def read_ppt(ppt_file, keywords=''):
prs = Presentation(ppt_file)
is_in = False
for slide in prs.slides:
for shape in slide.shapes:
if shape.has_text_frame:
text_frame = shape.text_frame
for paragraph in text_frame.paragraphs:
for run in paragraph.runs:
if run.text.find(keywords) != -1:
is_in = True
break
return is_in
def list_files_recursive(directory):
file_paths = []
for path in Path(directory).rglob('*'):
if path.is_file():
file_paths.append(str(path))
return file_paths
if __name__ == '__main__':
keywords = '測試關(guān)鍵字'
file_paths = list_files_recursive(r'測試文件夾')
for file_path in file_paths:
if file_path.endswith('.txt'):
is_in = read_txt(file_path, keywords)
elif file_path.endswith('.docx'):
is_in = read_docx(file_path, keywords)
elif file_path.endswith('.csv'):
is_in = read_csv(file_path, keywords)
elif file_path.endswith('.xlsx'):
is_in = read_xlsx(file_path, keywords)
elif file_path.endswith('.pptx'):
is_in = read_ppt(file_path, keywords)
if is_in:
print(file_path)結(jié)尾
現(xiàn)在你可以十分方便地使用代碼查找出各種文件中是否存在關(guān)鍵字了
以上就是Python實現(xiàn)文件查詢關(guān)鍵字功能的示例詳解的詳細內(nèi)容,更多關(guān)于Python查詢文件關(guān)鍵字的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
PyTorch加載數(shù)據(jù)集梯度下降優(yōu)化
這篇文章主要介紹了PyTorch加載數(shù)據(jù)集梯度下降優(yōu)化,使用DataLoader方法,并繼承DataSet抽象類,可實現(xiàn)對數(shù)據(jù)集進行mini_batch梯度下降優(yōu)化,需要的小伙伴可以參考一下2022-03-03
PyQt5每天必學(xué)之日歷控件QCalendarWidget
這篇文章主要為大家詳細介紹了PyQt5每天必學(xué)之日歷控件QCalendarWidget,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-04-04
Python Process創(chuàng)建進程的2種方法詳解
這篇文章主要介紹了Python Process創(chuàng)建進程的2種方法詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
Kmeans均值聚類算法原理以及Python如何實現(xiàn)
這個算法中文名為k均值聚類算法,首先我們在二維的特殊條件下討論其實現(xiàn)的過程,方便大家理解。2020-09-09
python爬蟲開發(fā)之Request模塊從安裝到詳細使用方法與實例全解
這篇文章主要介紹了python爬蟲開發(fā)之Request模塊從安裝到詳細使用方法與實例全解,需要的朋友可以參考下2020-03-03
Python實現(xiàn)HTTP網(wǎng)絡(luò)請求功能的入門指南
HTTP是互聯(lián)網(wǎng)上應(yīng)用最廣泛的通信協(xié)議,簡單來說,HTTP 網(wǎng)絡(luò)請求就是客戶端(如你的 Python 程序)向服務(wù)器發(fā)送消息,并等待服務(wù)器返回響應(yīng)的過程,本文給大家介紹了在Python中實現(xiàn)HTTP網(wǎng)絡(luò)請求功能的入門指南,需要的朋友可以參考下2026-05-05

