開発環境
- macOS Mojave - Apple (OS)
- Emacs (Text Editor)
- Windows 10 Pro (OS)
- Visual Studio Code (Text Editor)
- Python 3.7 (プログラミング言語)
退屈なことはPythonにやらせよう ―ノンプログラマーにもできる自動化処理プログラミング (Al Sweigart(著)、相川 愛三(翻訳)、オライリージャパン)の第Ⅱ部(処理の自動化)、8章(ファイルの読み書き)、8.10(演習プロジェクト)、8.10.3(正規表現検索)の解答を求めてみる。
コード
Python 3
#!/usr/bin/env python3
import os
import re
while True:
pattern = input('正規表現を入力: ')
if pattern == 'q':
break
for filename in os.listdir('.'):
if os.path.isfile(filename) and filename.endswith('.py'):
print(f'ファイル名: {filename}')
with open(filename) as f:
for line in f:
if re.search(pattern, line):
print(line, end='')
入出力結果(Bash、cmd.exe(コマンドプロンプト)、Terminal、Jupyter(IPython))
C:\Users\...>py sample3.py
正規表現を入力: if
ファイル名: sample1.py
if n == 3:
if cmd == 'save':
elif cmd == 'delete':
if key == 'all':
if key in shelf:
elif n == 2:
if argv1 == 'list':
elif argv1 in shelf:
ファイル名: sample3.py
if pattern == 'q':
if os.path.isfile(filename) and filename.endswith('.py'):
if re.search(pattern, line):
ファイル名: sample2.py
正規表現を入力: (if|for)
ファイル名: sample1.py
if n == 3:
if cmd == 'save':
elif cmd == 'delete':
if key == 'all':
if key in shelf:
elif n == 2:
if argv1 == 'list':
elif argv1 in shelf:
ファイル名: sample3.py
if pattern == 'q':
for filename in os.listdir('.'):
if os.path.isfile(filename) and filename.endswith('.py'):
for line in f:
if re.search(pattern, line):
ファイル名: sample2.py
for word in words:
正規表現を入力: q
C:\Users\...>
0 コメント:
コメントを投稿