Python デザインパターン サンプルコード Template Method
Mark Summerfield『実践 Python 3』デザインパターンのサンプルコード
Python3(3.11)で動くソースコード(.pyファイル .ipynbファイル)あります
「anaconda3」on .py「PyCharm」.ipynb「Jupyter Notebook」
(2023-11-17)Python3.11で動作確認済み
【重要な注意】本ソースコードファイルを起動するには第2引数が必要です。ターミナルからPythonを起動するとき,普通はプロンプト「'>'」の後に次のようにタイプします。
>python wordcount1.py pythonpattern01.html(ケースバイケースで)
ターミナルによっては'python'は'python3'になります。ソースコードファイル(スクリプトファイル)名称が第1引数です。第2引数は本プログラムに読み込むオプションです。
「PyCharm」では,次の枠に第2引数を設定します。
メニュー→run→Edit Configurations...→左下矢印と右上矢印の枠
ファイル名→Modify Run Configuration...→左下矢印と右上矢印の枠
画面によっては,Interpreter options: という枠です(左下矢印と右上矢印の枠)
「Jupyter Notebook」では,自己テストの1行目に「sys.argv[1]=」を入れます。「PyCharm」では,この行はありません。「Jupyter Notebook」にこの行を入れるのは,ハードコードと言い,固有名詞や固有な数値をコマンドラインに埋め込むことは本来避けるべきですが,この場合はやむを得ないとしましょう。ちなみにこのコードでは第1引数のような扱いになっていますが,ターミナルのコマンドラインでは第2引数なので混乱しないように。
「sys.argv[1]=」の前かまたは冒頭に「import sys」を忘れないように。
.pyではターミナルから実行されたとき自己テストが実行され,他のファイルから呼ばれたときは自己テストは無視されることも忘れないように。「Jupyter Notebook」では呼ばれる側を上側に置き,下側に参照されるようにします(本記事に関係ないかも)。
AbstractWordCounter (can_count, count) ↑ ↑ PlainTextWordCounter HtmlWordCounter (can_count, count) (can_count, count)サンプルは,プレーンテキストファイル(拡張子;txt)またはHTMLファイル(拡張子;html/htm)のワード数を数えるものです。
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
#!/usr/bin/env python3 # Copyright c 2012-13 Qtrac Ltd. All rights reserved. # This program or module is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. It is provided for educational # purposes and is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. import html.parser import os import re import sys def main(): if len(sys.argv) == 1 or sys.argv[1] in {"-h", "--help"}: print("usage: {} <files>".format(os.path.basename(sys.argv[0]))) sys.exit(1) count_words_in_files(sys.argv[1:]) def count_words_in_files(files): total = 0 for filename in files: count = count_words(filename) if count is not None: total += count print("{:9,} words in {}".format(count, filename)) print("total: {:,} words".format(total)) def count_words(filename): for wordCounter in (PlainTextWordCounter, HtmlWordCounter): if wordCounter.can_count(filename): return wordCounter.count(filename) class AbstractWordCounter: @staticmethod def can_count(filename): raise NotImplementedError() @staticmethod def count(filename): raise NotImplementedError() class PlainTextWordCounter(AbstractWordCounter): @staticmethod def can_count(filename): return filename.lower().endswith(".txt") @staticmethod def count(filename): if not PlainTextWordCounter.can_count(filename): return 0 regex = re.compile(r"\w+") total = 0 with open(filename, encoding="utf-8") as file: for line in file: for _ in regex.finditer(line): total += 1 return total class HtmlWordCounter(AbstractWordCounter): class __HtmlParser(html.parser.HTMLParser): def __init__(self): super().__init__() self.regex = re.compile(r"\w+") self.inText = True self.text = [] self.count = 0 def handle_starttag(self, tag, attrs): if tag in {"script", "style"}: self.inText = False def handle_endtag(self, tag): if tag in {"script", "style"}: self.inText = True else: for _ in self.regex.finditer(" ".join(self.text)): self.count += 1 self.text = [] def handle_data(self, text): if self.inText: text = text.rstrip() if text: self.text.append(text) @staticmethod def can_count(filename): return filename.lower().endswith((".htm", ".html")) @staticmethod def count(filename): if not HtmlWordCounter.can_count(filename): return 0 parser = HtmlWordCounter.__HtmlParser() with open(filename, encoding="utf-8") as file: parser.feed(file.read()) return parser.count if __name__ == "__main__": main()
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
#!/usr/bin/env python3 # Copyright c 2012-13 Qtrac Ltd. All rights reserved. # This program or module is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. It is provided for educational # purposes and is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. import abc import html.parser import os import re import sys def main(): if len(sys.argv) == 1 or sys.argv[1] in {"-h", "--help"}: print("usage: {} <files>".format(os.path.basename(sys.argv[0]))) sys.exit(1) count_words_in_files(sys.argv[1:]) def count_words_in_files(files): total = 0 for filename in files: count = count_words(filename) if count is not None: total += count print("{:9,} words in {}".format(count, filename)) print("total: {:,} words".format(total)) def count_words(filename): for wordCounter in (PlainTextWordCounter, HtmlWordCounter): if wordCounter.can_count(filename): return wordCounter.count(filename) class AbstractWordCounter( metaclass=abc.ABCMeta): @staticmethod @abc.abstractmethod def can_count(filename): pass @staticmethod @abc.abstractmethod def count(filename): pass class PlainTextWordCounter(AbstractWordCounter): @staticmethod def can_count(filename): return filename.lower().endswith(".txt") @staticmethod def count(filename): if not PlainTextWordCounter.can_count(filename): return 0 regex = re.compile(r"\w+") total = 0 with open(filename, encoding="utf-8") as file: for line in file: for _ in regex.finditer(line): total += 1 return total class HtmlWordCounter(AbstractWordCounter): class __HtmlParser(html.parser.HTMLParser): def __init__(self): super().__init__() self.regex = re.compile(r"\w+") self.inText = True self.text = [] self.count = 0 def handle_starttag(self, tag, attrs): if tag in {"script", "style"}: self.inText = False def handle_endtag(self, tag): if tag in {"script", "style"}: self.inText = True else: for _ in self.regex.finditer(" ".join(self.text)): self.count += 1 self.text = [] def handle_data(self, text): if self.inText: text = text.rstrip() if text: self.text.append(text) @staticmethod def can_count(filename): return filename.lower().endswith((".htm", ".html")) @staticmethod def count(filename): if not HtmlWordCounter.can_count(filename): return 0 parser = HtmlWordCounter.__HtmlParser() with open(filename, encoding="utf-8") as file: parser.feed(file.read()) return parser.count if __name__ == "__main__": main()