最近被新聞專業(yè)同學(xué)問起一個(gè)很實(shí)用的需求缀雳,大致是這樣的:一個(gè)文件夾內(nèi)有很多文件购啄,怎么通過搜索關(guān)鍵字就可以找到內(nèi)容包含關(guān)鍵字的word文件,同時(shí)獲得關(guān)鍵字所在段落的內(nèi)容寒随。由于最近在學(xué)習(xí)Python卖丸,所以對(duì)這個(gè)需求很感興趣纺且,于是當(dāng)時(shí)很快就把這個(gè)功能做出來了。
首先想到的自然是用腳本實(shí)現(xiàn)稍浆,新建一個(gè)kword.py文件载碌,差不讀四十幾行代碼將可以實(shí)現(xiàn),步驟是這樣的:
1.先獲取文件夾里面的所有文件路徑衅枫、其中用遞歸算法獲取子文件夾內(nèi)的文件路徑:
def get_process_files(root_dir):
"""process all files in directory"""
cur_dir=os.path.abspath(root_dir)
file_list=os.listdir(cur_dir)
process_list=[]
for file in file_list:
fullfile=cur_dir+"\\"+file
if os.path.isfile(fullfile):
process_list.append(fullfile)
elif os.path.isdir(fullfile):
dir_extra_list=get_process_files(fullfile)
if len(dir_extra_list)!=0:
for x in dir_extra_list:
process_list.append(x)
return process_list
2.利用python-docx模塊中的Document方法對(duì)word文件中每一段進(jìn)行關(guān)鍵字匹配:
def search_word(filename,word):
#打開文檔
document = Document(filename)
# document = Document(r'C:\Users\Cheng\Desktop\kword\words\wind.docx')
print filename
#讀取每段資料
l = [ paragraph.text.encode('gb2312') for paragraph in document.paragraphs];
#輸出并觀察結(jié)果嫁艇,也可以通過其他手段處理文本即可
for i in l:
i=i.strip()
# print i
if i.find(word)!=-1:
print filename, i
3.遍歷每一個(gè)文件并進(jìn)行查找:
def find_files(root_dir,word):
process_list=get_process_files(root_dir)
for files in process_list:
search_word(files, word)
這里有兩個(gè)參數(shù)需要我們自己輸入,分別是文件目錄和關(guān)鍵字弦撩。
#文件根目錄
root_dir=sys.argv[1]
#要搜索的關(guān)鍵字
word=sys.argv[2]
至此步咪,在腳本目錄下運(yùn)行“python kword.py 目錄 關(guān)鍵字”命令就可以看到搜索結(jié)果,目前搜索功能比較簡單益楼,沒有做大量文件測(cè)試和算法優(yōu)化猾漫。
獻(xiàn)上腳本源碼:
#coding=utf-8
from docx import Document
import os,sys
def search_word(filename,word):
#打開文檔
document = Document(filename)
# document = Document(r'C:\Users\Cheng\Desktop\kword\words\wind.docx')
print filename
#讀取每段資料
l = [ paragraph.text.encode('gb2312') for paragraph in document.paragraphs];
#輸出并觀察結(jié)果纯丸,也可以通過其他手段處理文本即可
for i in l:
i=i.strip()
# print i
if i.find(word)!=-1:
print filename, i
def get_process_files(root_dir):
"""process all files in directory"""
cur_dir=os.path.abspath(root_dir)
file_list=os.listdir(cur_dir)
process_list=[]
for file in file_list:
fullfile=cur_dir+"\\"+file
if os.path.isfile(fullfile):
process_list.append(fullfile)
elif os.path.isdir(fullfile):
dir_extra_list=get_process_files(fullfile)
if len(dir_extra_list)!=0:
for x in dir_extra_list:
process_list.append(x)
return process_list
def find_files(root_dir,word):
process_list=get_process_files(root_dir)
for files in process_list:
search_word(files, word)
if __name__=='__main__':
#文件根目錄
root_dir=sys.argv[1]
#要搜索的關(guān)鍵字
word=sys.argv[2]
try:
find_files(root_dir,word)
except:
pass
如果你喜歡本文章,還請(qǐng)點(diǎn)個(gè)關(guān)注和喜歡静袖,我會(huì)為大家不斷地帶來Python學(xué)習(xí)筆記。