Tod Naturlich/script/map maker.py
Jump to navigation
Jump to search
- !/usr/bin/env python3
- Sample input file, 2 spaces to indent each level.
- Disciplinary Action
- Disciplinary Office
- First Week
- Beatriz
- First Quarter
- First Year
- Primer
- Segundo
- Primo
- Second Year
- Last Year
import argparse import logging import sys from pathlib import Path
header =
{title} — Map
[[{title}|← Back]]
class MapMaker:
"""Creates a nice looking map form a list of nodes."""
_lines = None
def __init__(self, input, output): self.input_path = Path(input) self.output_path = Path(output) self.validate_input() self.validate_output()
def validate_input(self): if not self.input_path.exists() or self.input_path.is_dir(): raise ValueError('Missing file "' + self.input_path.name + '"')
def validate_output(self): if self.output_path.is_dir(): raise ValueError('"' + self.output_path.name + ' is a directory."')
def clean_line(self): tmp = [] for line in self._lines: space_no = len(line) - len(line.lstrip()) clean_line = line.strip() tmp.append([space_no // 2, clean_line]) self._lines = [value for value in tmp if len(value[1]) > 0]
@property def lines(self): if not self._lines: f = open(str(self.input_path),) self._lines = f.readlines() f.close() self.clean_line() return self._lines
def create_map(self): if len(self.lines) < 1: raise ValueError('"' + self.input_path.name + ' is empty."')
result = header.format(title=self.lines[0][1])
result += '\n\n
- \n'
levels = []
for index, line in enumerate(self.lines):
if index == len(self.lines) - 1:
next_level = 0
else:
next_level = self.lines[index + 1][0]
temp = '<li'
if next_level > line[0]:
temp += ' class="mw-collapsible mw-collapsed" data-expandtext="+" data-collapsetext="+"'
temp += '>'
levels.append(line[1])
temp += '' + line[1] + ''
if next_level > line[0]:
temp += '\n
- \n'
else:
temp += '\n'
temp += '
for _ in range(line[0] - next_level + 1): levels.pop() result += tempresult += '
\n\n'
result += '\n\n' f = open(str(self.output_path), 'w') f.write(result) f.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser( description='creates a nice looking map from an indented list of items.') parser.add_argument('file_path', help='filename of the text to parse.', metavar='file') parser.add_argument('destination_path', help='filename of the destinarion map.', metavar='destination') args = parser.parse_args()
try: map_maker = MapMaker(args.file_path, args.destination_path) except ValueError as e: logging.error(str(e)) sys.exit(1)
map_maker.create_map()