Python: テキスト処理のためのヘルパー関数
AWKのようなテキスト処理に特化した作業を Python で楽に行うための関数を作った。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #!/usr/bin/env python # -*- coding: utf-8 -*- """ Helper function for text stream processing """ import sys def process(function): paths = (sys.argv + [ None ])[ 1 : max ( 2 , len (sys.argv))] for path in paths: try : fp = sys.stdin if path is None else open (path) for line in fp: function(line.rstrip( "\n" )) except (KeyboardInterrupt, EOFError): pass except Exception: exc_type, exc = sys.exc_info()[: 2 ] print ( '%s: %s: %s' % (sys.argv[ 0 ], exc_type.__name__, exc)) |
コマンドライン引数が指定されない場合は標準入力から、指定された場合はそれぞれの引数をファイルパスと
見なして全ての入力を順に1行ずつ読み込み、何らかの処理を行う。
process 関数の引数にはパラメータを1個取る関数を渡す。
そのパラメータには、読み込まれた入力が1行ずつ、末尾の改行が除去された文字列として渡される。
利用例
入力をそのまま標準出力へ出力するだけの処理
1 2 3 4 5 6 7 8 9 10 11 12 | #!/usr/bin/env python # -*- coding: utf-8 -*- import textprocessor def identity(line): print (line) if __name__ = = '__main__' : textprocessor.process(identity) |
実行例
- 準備したファイル
1 2 | line1 line2 |
- 標準入力から流し込む
1 2 3 | $ cat ./test.txt | ./identity.py line1 line2 |
- ファイルパスを指定して実行
1 2 3 | $ ./identity.py ./test.txt line1 line2 |
- 複数のファイルを指定して実行
1 2 3 4 5 | $ ./identity.py ./test.txt ./test.txt line1 line2 line1 line2 |
- エラーケース
1 2 | $ ./identity.py xxxxxx ./identity.py: IOError: [Errno 2] No such file or directory: 'xxxxxx' |
0 件のコメント:
コメントを投稿