1+ import os
12import re
2- from typing import List , Dict
3+ import shutil
4+ from functools import reduce
5+ from pathlib import Path
6+ from string import Template
7+ from typing import Dict , List
8+
9+ width_chars = 64
10+ template_str : str = \
11+ f'''
12+ #!/usr/bin/env python
13+ # -*- coding:utf-8 -*-
14+ #
15+ { '#' * width_chars }
16+ #
17+ $title
18+ $level
19+ #
20+ { '#' * width_chars }
21+ #
22+ $question
23+ #
24+ $hints
25+ #
26+ { '#' * width_chars }
27+ '''
28+ tempate : Template = Template (template_str )
29+
30+ questions_file_name : str = 'Python-programming-exercises/100+ Python challenging programming exercises.txt'
31+ questions_file_title_offset : int = 2
32+ dist_dir_name : str = 'my_exercises'
33+
34+ Path (dist_dir_name ).mkdir (parents = True , exist_ok = True )
35+ shutil .rmtree (dist_dir_name )
36+ Path (dist_dir_name ).mkdir (parents = True , exist_ok = True )
337
4- file_name : str = 'Python-programming-exercises/100+ Python challenging programming exercises.txt'
538
639buffer : str = None
7- with open (file_name , 'r' ) as f :
40+ with open (questions_file_name , 'r' ) as f :
841 buffer = f .read ()
942
1043questions : List = re .split (r'#[-]+#' , buffer )
1144questions = [str (x ).strip () for x in questions if len (str (x ).strip ()) > 0 ]
1245
13- for i in range (2 , len (questions )):
46+ for i in range (questions_file_title_offset , len (questions )):
1447 one : str = questions [i ]
1548 lines : List [str ] = [x for x in one .split ('\n ' ) if len (str (x ).strip ()) > 0 ]
1649
3467 key = 'hints'
3568 elif line .startswith ('Solution' ):
3669 key = 'solution'
37-
70+
3871 if key == '' :
3972 continue
40-
73+
4174 data [key ] += f'{ line } \n '
4275
43- print ( f'title: \t { data [ "title" ] } ' )
44- print ( f'level: \t { data [ "level" ] } ' )
45- print ( f'question: \t { data [ "question" ] } ' )
46- print ( f'hints: \t { data [ "hints" ] } ' )
47- print ( f'solution: \t { data [ "solution" ] } ' )
76+ source : str = tempate . substitute ( data )
77+ lines : List = source . split ( ' \n ' )
78+ lines = [ x for x in lines if len ( x ) > 0 ]
79+ lines = map ( lambda a : a if str ( a ). startswith ( '#' ) else '# ' + a , lines )
80+ source = reduce ( lambda a , b : a + ' \n ' + b , lines )
4881
49- print ('#' * 20 )
82+ source_file_name : str = f'question_{ i - 1 } .py'
83+ with open (os .path .join (dist_dir_name , source_file_name ), 'w' ) as f :
84+ f .write (source )
0 commit comments