これまでWord、PDF、Excelファイルをgrep検索するプログラムを紹介してきました。今回は1つのプログラムでこれらすべてのファイルをgrep検索するプログラムを紹介します。つまり、これまでのプログラムを1つにまとめてみたということです。ただ1つにまとめただけでなく、テストファイル(txt)もgrep検索できるようにしてあります。
使い方

検索ボックスの下に検索対象としたいファイルのプログラム(Word, Excel, PowerPoint, PDF, テキスト)をチェックボックスで指定できるようにしてあります。それ以外については以前のプログラムと同じ使い方ですので、そちらを参照してください。
必要モジュール
すでに紹介してきたように以下のモジュールをインストールする必要があります。
|
1 2 3 4 |
pip install docx2txt pip install pdfminer.six pip install python-pptx pip install xlrd |
また今回、初期設定ファイル(iniファイル)を使っているので以下のモジュールも必要になります。
|
1 |
pip install configparser |
ソースコード
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 |
import docx2txt import xlrd from pptx import Presentation from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import TextConverter from pdfminer.layout import LAParams from pdfminer.pdfpage import PDFPage from io import StringIO import os import re import tkinter as tk import tkinter.filedialog as fd from tkinter import messagebox import subprocess from glob import glob import configparser ############################################################################### # # 検索結果を保持するデータクラス # ############################################################################### class Result(): def __init__(self): self.dir_name = "" self.filename = "" self.line = -1 self.sentence = "" class ResultPptx(): def __init__(self): self.dir_name = "" self.filename = "" self.slide_no = -1 self.sentence = "" class ResultExcel(): def __init__(self): self.dir_name = "" self.filename = "" self.sheetname = "" self.sentence = "" ############################################################################### # # メインのGUIクラス # ############################################################################### class GUI_grep(): #-------------------------------------------------------------------------# # メインループ #-------------------------------------------------------------------------# def run(self): self.root.mainloop() #-------------------------------------------------------------------------# # 初期化 #-------------------------------------------------------------------------# def __init__(self): self.dirpath = "" self.root = tk.Tk() self.root.title(u"grep検索") self.frame1 = tk.Frame() self.frame1.pack() self.kw_entry = tk.Entry(self.frame1, width=100) self.kw_entry.pack(fill='x', padx=10, side='left') self.button_grep = tk.Button(self.frame1, text="find", width=10, command=self.process_files) self.button_grep.pack(fill='x', padx=10, side='left') self.frame2 = tk.Frame() self.frame2.pack(anchor=tk.E, padx=20) self.b_chk_w = tk.BooleanVar(value=True) # word self.b_chk_e = tk.BooleanVar(value=True) # excel self.b_chk_p = tk.BooleanVar(value=True) # pptx self.b_chk_f = tk.BooleanVar(value=True) # pdf self.b_chk_t = tk.BooleanVar(value=True) # txt self.chk_btn_w = tk.Checkbutton(self.frame2, variable=self.b_chk_w, text='Word') self.chk_btn_w.pack(fill='x', side='left') self.chk_btn_e = tk.Checkbutton(self.frame2, variable=self.b_chk_e, text='Excel') self.chk_btn_e.pack(fill='x', side='left') self.chk_btn_p = tk.Checkbutton(self.frame2, variable=self.b_chk_p, text='PowerPoint') self.chk_btn_p.pack(fill='x', side='left') self.chk_btn_f = tk.Checkbutton(self.frame2, variable=self.b_chk_f, text='PDF') self.chk_btn_f.pack(fill='x', side='left') self.chk_btn_t = tk.Checkbutton(self.frame2, variable=self.b_chk_t, text='txt') self.chk_btn_t.pack(fill='x', side='left') self.frame3 = tk.Frame() self.frame3.pack(anchor=tk.E, padx=20) self.b_chk1 = tk.BooleanVar(value=True) self.chk_btn1 = tk.Checkbutton(self.frame3, variable=self.b_chk1, text='recursive') self.chk_btn1.pack() self.frame4 = tk.Frame() self.frame4.pack() self.dir_entry = tk.Entry(self.frame4, width=100) self.dir_entry.configure(state='readonly') self.dir_entry.pack(fill='x', padx=10, side='left') self.button_mov = tk.Button(self.frame4, text="folder...", width=10, command=self.set_directory) self.button_mov.pack(fill='x', padx=10, side='left') self.frame5 = tk.Frame() self.frame5.pack() self.text = tk.Text(self.frame5, width=100, height=30, wrap=tk.NONE) self.text.bind("<Double-1>", self.open_file) self.yscroll = tk.Scrollbar(self.frame5, orient=tk.VERTICAL, command=self.text.yview) self.yscroll.pack(side=tk.RIGHT, fill="y") self.xscroll = tk.Scrollbar(self.frame5, orient=tk.HORIZONTAL, command=self.text.xview) self.xscroll.pack(side=tk.BOTTOM, fill="x") self.text["yscrollcommand"] = self.yscroll.set self.text["xscrollcommand"] = self.xscroll.set self.text.pack(side='top') # 結果を格納するリスト self.all_results_w = [] self.all_results_e = [] self.all_results_p = [] self.all_results_f = [] self.all_results_t = [] # 初期設定ファイル if os.path.exists('config.ini'): config_ini = configparser.ConfigParser() config_ini.read('config.ini') self.prog_path_w = config_ini['WORD']['Path'] if self.prog_path_w == None: self.prog_path_w = '"C:\Program Files\Microsoft Office\Office16\WINWORD.EXE"' self.prog_path_e = config_ini['EXCEL']['Path'] if self.prog_path_e == None: self.prog_path_e = '"C:\Program Files\Microsoft Office\Office16\EXCEL.EXE"' self.prog_path_p = config_ini['POWERPOINT']['Path'] if self.prog_path_p == None: self.prog_path_p = '"C:\Program Files\Microsoft Office\Office16\POWERPNT.EXE"' self.prog_path_f = config_ini['PDF']['Path'] if self.prog_path_f == None: self.prog_path_f = '"C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe"' self.prog_path_t = config_ini['TEXT']['Path'] if self.prog_path_t == None: self.prog_path_t = '"C:\Windows\System32\notepad.exe"' else: self.prog_path_w = '"C:\Program Files\Microsoft Office\Office16\WINWORD.EXE"' self.prog_path_e = '"C:\Program Files\Microsoft Office\Office16\EXCEL.EXE"' self.prog_path_p = '"C:\Program Files\Microsoft Office\Office16\POWERPNT.EXE"' self.prog_path_f = '"C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe"' self.prog_path_t = '"C:\Windows\System32\notepad.exe"' #-------------------------------------------------------------------------# # 検索結果をダブルクリックして、ファイルを開く処理 #-------------------------------------------------------------------------# def open_file(self, event): pos = self.text.index('insert') try: line_n = int(pos.split('.')[0]) # クリックされた行番号 num_w = len(self.all_results_w) num_e = len(self.all_results_e) num_p = len(self.all_results_p) num_f = len(self.all_results_f) num_t = len(self.all_results_t) if line_n <= num_w: pass res = self.all_results_w[line_n] prog_path = self.prog_path_w elif line_n <= num_w + num_e: line_n = line_n - num_w - 1 res = self.all_results_e[line_n] prog_path = self.prog_path_e elif line_n <= num_w + num_e + num_p: line_n = line_n - num_w - num_e - 1 res = self.all_results_p[line_n] prog_path = self.prog_path_p elif line_n <= num_w + num_e + num_p + num_f: line_n = line_n - num_w - num_e - num_p - 1 res = self.all_results_f[line_n] prog_path = self.prog_path_f elif line_n <= num_w + num_e + num_p + num_f + num_t: line_n = line_n - num_w - num_e - num_p - num_f - 1 res = self.all_results_t[line_n] prog_path = self.prog_path_t else: return file_path = os.path.join(res.dir_name, res.filename) file_path = file_path.replace('/', '\\') command = f'{prog_path} "{file_path}"' subprocess.Popen(command, shell=False) except Exception as e: print(e) pass #-------------------------------------------------------------------------# # プログラムの終了処理 #-------------------------------------------------------------------------# def exit_program(self): self.root.quit() exit() #-------------------------------------------------------------------------# # ディレクトリ選択ダイアログ #-------------------------------------------------------------------------# def ask_input_directory(self): rt = tk.Tk() rt.withdraw() dir_name = fd.askdirectory(initialdir=os.getcwd(), title='フォルダの選択', mustexist=True) rt.destroy() return dir_name #-------------------------------------------------------------------------# # ディレクトリを設定する #-------------------------------------------------------------------------# def set_directory(self): self.dirpath = self.ask_input_directory() # キャンセルされた場合 if self.dirpath == '': return self.dir_entry.configure(state='normal') self.dir_entry.delete(0, tk.END) self.dir_entry.insert(tk.END, self.dirpath) self.dir_entry.configure(state='readonly') #-------------------------------------------------------------------------# # Grep検索する #-------------------------------------------------------------------------# def process_files(self): # ディレクトリが設定されていない場合 if self.dir_entry.get() == '': self.set_directory() if self.dirpath == '': self.dirpath == self.dir_entry.get() if self.dirpath == '': return # キーワード keyword = self.kw_entry.get() # 検索結果をクリアする self.text.delete("1.0", "end") self.all_results_w = [] self.all_results_e = [] self.all_results_p = [] self.all_results_f = [] self.all_results_t = [] if self.b_chk1.get() == True: all_files = glob(self.dirpath + "/**/*.*", recursive=True) else: all_files = glob(self.dirpath + "/*.*") for file in all_files: filename = os.path.basename(file) print(filename) # 拡張子のチェック ext = filename.split('.')[-1] if ext == 'docx' and self.b_chk_w.get() == True: self.process_files_docx(file, self.all_results_w, keyword) elif ext == 'xlsx' and self.b_chk_e.get() == True: self.process_files_xlsx(file, self.all_results_e, keyword) elif ext == 'pptx' and self.b_chk_p.get() == True: self.process_files_pptx(file, self.all_results_p, keyword) elif ext == 'pdf' and self.b_chk_f.get() == True: self.process_files_pdf(file, self.all_results_f, keyword) elif ext == 'txt' and self.b_chk_t.get() == True: self.process_files_txt(file, self.all_results_t, keyword) else: continue # 結果の表示 # Word for i, res in enumerate(self.all_results_w): self.text.insert(tk.END, f"{res.filename} ({res.line}): {res.sentence}\n") # Excel for i, res in enumerate(self.all_results_e): self.text.insert(tk.END, f"{res.filename} ({res.sheetname}): {res.sentence}\n") # PowerPoint for i, res in enumerate(self.all_results_p): self.text.insert(tk.END, f"{res.filename} ({res.slide_no}): {res.sentence}\n") # PDF for i, res in enumerate(self.all_results_f): self.text.insert(tk.END, f"{res.filename} ({res.line}): {res.sentence}\n") # txt for i, res in enumerate(self.all_results_t): self.text.insert(tk.END, f"{res.filename} ({res.line}): {res.sentence}\n") messagebox.showinfo("終了", "検索が終わりました。") #-------------------------------------------------------------------------# def process_files_docx(self, file, all_results, keyword): dir_name = os.path.dirname(file) filename = os.path.basename(file) text = docx2txt.process(file) ## 不要な改行を取り除く text = re.sub(r'\n+', '\n', text) lines = text.split('\n') for i in range(len(lines)): m = re.search(keyword, lines[i]) if m: res = Result() res.dir_name = dir_name res.filename = filename res.line = i res.sentence = lines[i] all_results.append(res) def process_files_xlsx(self, file, all_results, keyword): dir_name = os.path.dirname(file) filename = os.path.basename(file) wb = xlrd.open_workbook(file) sheet_names = wb.sheet_names() sheet_num = len(sheet_names) for sheet in range(int(sheet_num)): ws = wb.sheet_by_index(sheet) for row in ws.get_rows(): for c in row: try: m = re.search(keyword, c.value) if m: res = ResultExcel() res.dir_name = dir_name res.filename = filename res.sheetname = sheet_names[sheet] res.sentence = c.value all_results.append(res) except Exception as e: print(e) pass def process_files_pptx(self, file, all_results, keyword): dir_name = os.path.dirname(file) filename = os.path.basename(file) pptx = Presentation(file) for i, slide in enumerate(pptx.slides): # シェイプの検索 for shape in slide.shapes: # 文字を含まないシェイプは飛ばす if not shape.has_text_frame: continue for par in shape.text_frame.paragraphs: for run in par.runs: try: m = re.search(keyword, run.text) if m: res = ResultPptx() res.dir_name = dir_name res.filename = filename res.slide_no = i + 1 res.sentence = run.text all_results.append(res) except Exception as e: print(e) pass # ノートの検索 try: text = slide.notes_slide.notes_text_frame.text text = text.replace('\n', '') m = re.search(keyword, text) if m: res = ResultPptx() res.dir_name = dir_name res.filename = filename res.slide_no = i + 1 res.sentence = text self.all_results.append(res) except Exception as e: print(e) pass def process_files_pdf(self, file, all_results, keyword): dir_name = os.path.dirname(file) filename = os.path.basename(file) rsrcmgr = PDFResourceManager() laparams = LAParams() laparams.detect_vertical = True outfp = StringIO() device = TextConverter(rsrcmgr, outfp, codec='utf-8', laparams=laparams) pdf = open(file, 'rb') interpreter = PDFPageInterpreter(rsrcmgr, device) for page in PDFPage.get_pages(pdf): interpreter.process_page(page) text =[outfp.getvalue()] pdf.close() device.close() outfp.close() for i in range(len(text)): try: lines = re.sub(r'\n+', '\n', text[i]) lines = lines.split('\n') for ii in range(len(lines)): m = re.search(keyword, lines[ii]) if m: res = Result() res.dir_name = dir_name res.filename = filename res.line = ii+1 res.sentence = lines[ii] all_results.append(res) except Exception as e: print(e) pass def process_files_txt(self, file, all_results, keyword): dir_name = os.path.dirname(file) filename = os.path.basename(file) f = open(file, 'r') text = f.readlines() f.close() for i in range(len(text)): try: lines = re.sub(r'\n+', '\n', text[i]) lines = lines.split('\n') for ii in range(len(lines)): m = re.search(keyword, lines[ii]) if m: res = Result() res.dir_name = dir_name res.filename = filename res.line = i+1 res.sentence = lines[ii] all_results.append(res) except Exception as e: print(e) pass ############################################################################### # # 以下、メイン処理 # ############################################################################### if __name__ == "__main__": app = GUI_grep() app.run() |
プログラムの簡単な説明
|
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
class Result(): def __init__(self): self.dir_name = "" self.filename = "" self.line = -1 self.sentence = "" class ResultPptx(): def __init__(self): self.dir_name = "" self.filename = "" self.slide_no = -1 self.sentence = "" class ResultExcel(): def __init__(self): self.dir_name = "" self.filename = "" self.sheetname = "" self.sentence = "" |
23~45行目:検索結果を格納するクラスを定義しています。
Resultクラス:Word、PDF、テキストファイル用の結果クラス
ResultPptxクラス:PowerPointファイルの結果クラス
ResultExcelクラス:Excelファイルの結果クラス
|
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 |
if os.path.exists('config.ini'): config_ini = configparser.ConfigParser() config_ini.read('config.ini') self.prog_path_w = config_ini['WORD']['Path'] if self.prog_path_w == None: self.prog_path_w = '"C:\Program Files\Microsoft Office\Office16\WINWORD.EXE"' self.prog_path_e = config_ini['EXCEL']['Path'] if self.prog_path_e == None: self.prog_path_e = '"C:\Program Files\Microsoft Office\Office16\EXCEL.EXE"' self.prog_path_p = config_ini['POWERPOINT']['Path'] if self.prog_path_p == None: self.prog_path_p = '"C:\Program Files\Microsoft Office\Office16\POWERPNT.EXE"' self.prog_path_f = config_ini['PDF']['Path'] if self.prog_path_f == None: self.prog_path_f = '"C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe"' self.prog_path_t = config_ini['TEXT']['Path'] if self.prog_path_t == None: self.prog_path_t = '"C:\Windows\System32\notepad.exe"' else: self.prog_path_w = '"C:\Program Files\Microsoft Office\Office16\WINWORD.EXE"' self.prog_path_e = '"C:\Program Files\Microsoft Office\Office16\EXCEL.EXE"' self.prog_path_p = '"C:\Program Files\Microsoft Office\Office16\POWERPNT.EXE"' self.prog_path_f = '"C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe"' self.prog_path_t = '"C:\Windows\System32\notepad.exe"' |
140~171行目:configparserモジュールを用いて「config.ini」という初期設定ファイルを読み込み、Word、Excel、PowerPoint、PDF、テキストエディタのパスを指定しています。「config.ini」がない場合はデフォルトのパスを指定しています。
config.iniは以下のようなファイルで、各プログラムについて変数Pathに実行ファイルの場所を指定しています。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
[WORD] Path = "C:\Program Files\Microsoft Office\root\Office16\WINWORD.EXE" [EXCEL] Path = "C:\Program Files\Microsoft Office\root\Office16\EXCEL.EXE" [POWERPOINT] Path = "C:\Program Files\Microsoft Office\root\Office16\POWERPNT.EXE" [PDF] Path = "C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe" [TEXT] Path = "C:\Windows\System32\notepad.exe" |
|
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 |
if self.b_chk1.get() == True: all_files = glob(self.dirpath + "/**/*.*", recursive=True) else: all_files = glob(self.dirpath + "/*.*") for file in all_files: filename = os.path.basename(file) print(filename) # 拡張子のチェック ext = filename.split('.')[-1] if ext == 'docx' and self.b_chk_w.get() == True: self.process_files_docx(file, self.all_results_w, keyword) elif ext == 'xlsx' and self.b_chk_e.get() == True: self.process_files_xlsx(file, self.all_results_e, keyword) elif ext == 'pptx' and self.b_chk_p.get() == True: self.process_files_pptx(file, self.all_results_p, keyword) elif ext == 'pdf' and self.b_chk_f.get() == True: self.process_files_pdf(file, self.all_results_f, keyword) elif ext == 'txt' and self.b_chk_t.get() == True: self.process_files_txt(file, self.all_results_t, keyword) else: continue |
277~299行目:globを使ってファイルリストを読み出し、拡張子をチェックして、各ファイルタイプの処理に分岐させています。それぞれの処理内容は以前に紹介していますので、そちらをご覧ください。
拡張子がdocxの場合は、321行目にあるprocess_files_docxメソッド、
拡張子がxlsxの場合は、339行目にあるprocess_files_xlsxメソッド、
拡張子がpptxの場合は、363行目にあるprocess_files_pptxメソッド、
拡張子がpdfの場合は、404行目にあるprocess_files_pdfメソッド、
拡張子がtxtの場合は、442行目にあるprocess_files_txtメソッドに飛んでいます。
- 投稿タグ
- プログラミング