1
+ import os
1
2
import 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 )
3
37
4
- file_name : str = 'Python-programming-exercises/100+ Python challenging programming exercises.txt'
5
38
6
39
buffer : str = None
7
- with open (file_name , 'r' ) as f :
40
+ with open (questions_file_name , 'r' ) as f :
8
41
buffer = f .read ()
9
42
10
43
questions : List = re .split (r'#[-]+#' , buffer )
11
44
questions = [str (x ).strip () for x in questions if len (str (x ).strip ()) > 0 ]
12
45
13
- for i in range (2 , len (questions )):
46
+ for i in range (questions_file_title_offset , len (questions )):
14
47
one : str = questions [i ]
15
48
lines : List [str ] = [x for x in one .split ('\n ' ) if len (str (x ).strip ()) > 0 ]
16
49
34
67
key = 'hints'
35
68
elif line .startswith ('Solution' ):
36
69
key = 'solution'
37
-
70
+
38
71
if key == '' :
39
72
continue
40
-
73
+
41
74
data [key ] += f'{ line } \n '
42
75
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 )
48
81
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