2016年1月31日日曜日

開発環境

  • OS X El Capitan - Apple (OS)
  • Emacs (Text Editor)
  • Python 3.5 (プログラミング言語)

Automate the Boring Stuff with Python (Al Sweigart (著)、No Starch Press)のPart 2.(Automating Tasks)、Chapter 8.(Reading and Writing Files)、Practice Projects(Regex Search)(No. 4723)を取り組んでみる。

Practice Projects(Regex Search)(No. 4723)

コード(Emacs)

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

import re
import os

pattern = input('Enter a regular expression: ')
for filename in os.listdir('.'):
    if filename.endswith('.txt'):
        with open(filename) as f:
            for line in f:
                if re.match(pattern, line):
                    print(line, end='')

入出力結果(Terminal, IPython)

$ cat *.txt
The ADJECTIVE pand walked to the NOUN and then VERB.
A nearyby NOUN was unaffected by these events.
The silly pand walked to the chandelier and then screamed.
A nearyby pickup truck was unaffected by these events.
$ cat input.txt
The ADJECTIVE pand walked to the NOUN and then VERB.
A nearyby NOUN was unaffected by these events.
$ ./madlibs.py
Enter an adjective:
silly
Enter an noun:
chandelier
Enter an VERB:
screamed
Enter an noun:
pickup truck
The silly pand walked to the chandelier and then screamed.
A nearyby pickup truck was unaffected by these events.
$ cat out.txt 
The silly pand walked to the chandelier and then screamed.
A nearyby pickup truck was unaffected by these events.
$ 
$ ./regex_search.py
Enter a regular expression: ^\$.*$
$ cat input.txt
$ ./madlibs.py
$ cat out.txt 
$
$

0 コメント:

コメントを投稿