python操作word 查找_Python实现搜索关键字定位文件01
最近被新聞專業同學問起一個很實用的需求,大致是這樣的:一個文件夾內有很多文件,怎么通過搜索關鍵字就可以找到內容包含關鍵字的word文件,同時獲得關鍵字所在段落的內容。由于最近在學習Python,所以對這個需求很感興趣,于是當時很快就把這個功能做出來了。
首先想到的自然是用腳本實現,新建一個kword.py文件,差不讀四十幾行代碼將可以實現,步驟是這樣的:
1.先獲取文件夾里面的所有文件路徑、其中用遞歸算法獲取子文件夾內的文件路徑:
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方法對word文件中每一段進行關鍵字匹配:
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];
#輸出并觀察結果,也可以通過其他手段處理文本即可
for i in l:
i=i.strip()
# print i
if i.find(word)!=-1:
print filename, i
3.遍歷每一個文件并進行查找:
def find_files(root_dir,word):
process_list=get_process_files(root_dir)
for files in process_list:
search_word(files, word)
這里有兩個參數需要我們自己輸入,分別是文件目錄和關鍵字。
#文件根目錄
root_dir=sys.argv[1]
#要搜索的關鍵字
word=sys.argv[2]
至此,在腳本目錄下運行“python kword.py 目錄 關鍵字”命令就可以看到搜索結果,目前搜索功能比較簡單,沒有做大量文件測試和算法優化。
獻上腳本源碼:
#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];
#輸出并觀察結果,也可以通過其他手段處理文本即可
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]
#要搜索的關鍵字
word=sys.argv[2]
try:
find_files(root_dir,word)
except:
pass
如果你喜歡本文章,還請點個關注和喜歡,我會為大家不斷地帶來Python學習筆記。
總結
以上是生活随笔為你收集整理的python操作word 查找_Python实现搜索关键字定位文件01的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于数据库的事务消息解决分布式事务方案
- 下一篇: phaser设置图片资源大小