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

流程圖
怎么樣,思路非常簡(jiǎn)單,所以其實(shí)實(shí)現(xiàn)也不難。
本文將支持少部分文件類型,更多類型需要讀者自己實(shí)現(xiàn):
- txt
- docx
- csv
- xlsx
- pptx
讀取txt
安裝庫(kù)
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 庫(kù)來(lái)判斷 txt 的編碼,以應(yīng)對(duì)不同編碼的讀取方式。
讀取docx
安裝庫(kù)
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
安裝庫(kù)
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
安裝庫(kù)
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)致的問(wèn)題,我們還有一個(gè)文件夾遞歸的操作。
代碼
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 = '測(cè)試關(guān)鍵字'
file_paths = list_files_recursive(r'測(cè)試文件夾')
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實(shí)現(xiàn)文件查詢關(guān)鍵字功能的示例詳解的詳細(xì)內(nèi)容,更多關(guān)于Python查詢文件關(guān)鍵字的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
PyTorch加載數(shù)據(jù)集梯度下降優(yōu)化
這篇文章主要介紹了PyTorch加載數(shù)據(jù)集梯度下降優(yōu)化,使用DataLoader方法,并繼承DataSet抽象類,可實(shí)現(xiàn)對(duì)數(shù)據(jù)集進(jìn)行mini_batch梯度下降優(yōu)化,需要的小伙伴可以參考一下2022-03-03
Python logging日志模塊的核心用法與實(shí)操技巧
logging 是 Python 標(biāo)準(zhǔn)庫(kù)中的一個(gè)模塊,它提供了靈活的日志記錄功能,通過(guò) logging,開(kāi)發(fā)者可以方便地將日志信息輸出到控制臺(tái)、文件、網(wǎng)絡(luò)等多種目標(biāo),本文給大家介紹了Python logging日志模塊的核心用法與實(shí)操技巧,需要的朋友可以參考下2026-03-03
PyQt5每天必學(xué)之日歷控件QCalendarWidget
這篇文章主要為大家詳細(xì)介紹了PyQt5每天必學(xué)之日歷控件QCalendarWidget,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-04-04
Python Process創(chuàng)建進(jìn)程的2種方法詳解
這篇文章主要介紹了Python Process創(chuàng)建進(jìn)程的2種方法詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
Kmeans均值聚類算法原理以及Python如何實(shí)現(xiàn)
這個(gè)算法中文名為k均值聚類算法,首先我們?cè)诙S的特殊條件下討論其實(shí)現(xiàn)的過(guò)程,方便大家理解。2020-09-09
python爬蟲(chóng)開(kāi)發(fā)之Request模塊從安裝到詳細(xì)使用方法與實(shí)例全解
這篇文章主要介紹了python爬蟲(chóng)開(kāi)發(fā)之Request模塊從安裝到詳細(xì)使用方法與實(shí)例全解,需要的朋友可以參考下2020-03-03
Python實(shí)現(xiàn)HTTP網(wǎng)絡(luò)請(qǐng)求功能的入門(mén)指南
HTTP是互聯(lián)網(wǎng)上應(yīng)用最廣泛的通信協(xié)議,簡(jiǎn)單來(lái)說(shuō),HTTP 網(wǎng)絡(luò)請(qǐng)求就是客戶端(如你的 Python 程序)向服務(wù)器發(fā)送消息,并等待服務(wù)器返回響應(yīng)的過(guò)程,本文給大家介紹了在Python中實(shí)現(xiàn)HTTP網(wǎng)絡(luò)請(qǐng)求功能的入門(mén)指南,需要的朋友可以參考下2026-05-05

