LoginSignup
1
0

More than 3 years have passed since last update.

argparseを使ってgrep的なことをpythonで実行する

Last updated at Posted at 2019-09-18

概要

時々、pythonでキーワード検索したい時がある。
以下のコードをgrep.pyとして保存して、
python3 grep.py --text hoge.txt --keyword hoge とか入力すると、
UNIXのgrepと全く同様なことができるし、
--keywordを入れないでやれば、cat hoge.txt的な表示をする。
結構便利なのでメモ。

grep.py
import argparse

parser = argparse.ArgumentParser(description="This program extracts "
                                             "a keyword you want "
                                             "in a text file.")

parser.add_argument("--text", "-txt", dest="txt_path",
                    default="tmp", type=str,
                    help="Input the text file you want.")

parser.add_argument("--keyword", "-kw", dest="key_word",
                    default="none", type=str,
                    help="Input a keyword you want to extract.")

args = parser.parse_args()

with open(args.txt_path, "r") as tp:
    lines = tp.read()
    for l in lines.split("\n"):
        if f"{args.key_word}" in l:
            print(l)
        if f"{args.key_word}" == "none":
            print(l)

実行例

hoge.txt
Na4 Cl4
1.0
5.691694 0.000000 0.000000
0.000000 5.691694 0.000000
0.000000 0.000000 5.691694
Na Cl
4 4
direct
0.000000 0.000000 0.000000 Na
0.500000 0.500000 0.000000 Na
0.500000 0.000000 0.500000 Na
0.000000 0.500000 0.500000 Na
0.000000 0.000000 0.500000 Cl
0.500000 0.000000 0.000000 Cl
0.000000 0.500000 0.000000 Cl
0.500000 0.500000 0.500000 Cl
In [0]: python grep.py -txt hoge.txt -kw Na

Na4 Cl4
Na Cl
0.000000 0.000000 0.000000 Na
0.500000 0.500000 0.000000 Na
0.500000 0.000000 0.500000 Na
0.000000 0.500000 0.500000 Na

In [1]: python grep.py -txt hoge.txt -kw 5.6

5.691694 0.000000 0.000000
0.000000 5.691694 0.000000
0.000000 0.000000 5.691694

In [2]: python grep.py -txt hoge.txt

Na4 Cl4
1.0
5.691694 0.000000 0.000000
0.000000 5.691694 0.000000
0.000000 0.000000 5.691694
Na Cl
4 4
direct
0.000000 0.000000 0.000000 Na
0.500000 0.500000 0.000000 Na
0.500000 0.000000 0.500000 Na
0.000000 0.500000 0.500000 Na
0.000000 0.000000 0.500000 Cl
0.500000 0.000000 0.000000 Cl
0.000000 0.500000 0.000000 Cl
0.500000 0.500000 0.500000 Cl

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0