Belle II Software development
online_book_statistics.py
1#!/usr/bin/env python3
2
3
10
11"""
12This script calculates some numbers about the online book, e.g. number of
13exercises etc.
14"""
15
16from pathlib import Path
17import os
18import pprint
19import re
20
21
23 """
24 Statistics base class
25 """
26 def __init__(self):
27 """Initialize members"""
28
29 self.code_inclusions: int = 0
30
31 self.hints: int = 0
32
33 self.solutions: int = 0
34
35 self.exercises: int = 0
36
37 self.overview_boxes: int = 0
38
39 self.key_points: int = 0
40
41 self.figures: int = 0
42
43 self.characters: int = 0
44
45 def print_summary(self):
46 """Print the summary"""
47
48 pprint.pprint(self.__dict__)
49
50
52 """
53 Statistics visitor class
54 """
55
56 regexes = dict(
57 code_inclusions=re.compile("(code-block\\s*::)|(literalinclude\\s*::)"),
58 hints=re.compile(":class:.*hint"),
59 solutions=re.compile(":class:.*solution"),
60 exercises=re.compile(":class:.*exercise"),
61 overview_boxes=re.compile(":class:.*overview"),
62 key_points=re.compile(":class:.*key-points"),
63 figures=re.compile("figure\\s*::")
64 )
65
66 def __init__(self):
67 """Initialize class"""
68
70
71 def read_rst_file(self, path: Path):
72 """Read rst file"""
73 text = path.read_text()
74 self.statistics.characters += len(text)
75 for line in text.split("\n"):
76 for key, regex in self.regexes.items():
77 if regex.findall(line):
78 setattr(
79 self.statistics, key, getattr(self.statistics, key) + 1
80 )
81
82 def walk_directory(self, path: Path):
83 """Loop over all directories in the path"""
84 print(f"Walking {path}")
85 for root, _, files in os.walk(path):
86 for file in files:
87 path = Path(root) / file
88 if path.suffix == ".rst":
89 self.read_rst_file(path)
90
91
92def main():
93 this_dir = Path(__file__).resolve().parent
95 sv.walk_directory(this_dir)
96 sv.statistics.print_summary()
97
98
99if __name__ == "__main__":
100 main()
regexes
Dictionary keys must match attributes of Statistics class.
int overview_boxes
number of overview boxes
int code_inclusions
number of code inclusions
__dict__
printing using data pretty print
Definition main.py:1