1
- import requests
1
+ from collections import defaultdict
2
+ import json
3
+ import urllib .request
2
4
import argparse
3
5
import datetime
4
6
import html
5
7
import os
6
8
from pytablewriter import MarkdownTableWriter
7
9
10
+ __template = """
11
+ \" \" \"
12
+ 문제 이름: <problem_name>
13
+ 문제 번호: <problem_id>
14
+ 문제 링크: <url>
15
+ 난이도: <difficulty>
16
+ 태그: <tags>
17
+ \" \" \"
18
+ import sys
19
+
20
+ def input(): return sys.stdin.readline().rstrip()
21
+ """
8
22
__tier_text = {
9
23
0 : "Unknown" ,
10
24
1 : "Bronze V" ,
40
54
31 : "Master" ,
41
55
}
42
56
57
+
58
+ def make_problem_content (template , problem : dict ) -> str :
59
+ return template \
60
+ .replace ('<problem_name>' , problem ['name' ]) \
61
+ .replace ('<problem_id>' , str (problem ['id' ])) \
62
+ .replace ('<url>' , problem ['url' ]) \
63
+ .replace ('<difficulty>' , problem ['difficulty' ]) \
64
+ .replace ('<tags>' , ', ' .join (problem ['tags' ])) \
65
+
66
+
67
+
43
68
def write_all_text (path : str , text : str ) -> None :
44
69
f = open (path , 'w' )
45
70
f .write (text )
@@ -52,7 +77,9 @@ def make_problem_yaml(problem: dict) -> str:
52
77
lines .append (f"file: \" { problem ['id' ]} .md\" " )
53
78
lines .append (f"name: \" { problem ['name' ]} \" " )
54
79
lines .append (f"src: \" { problem ['url' ]} \" " )
55
- tags = '\n ' + '\n ' .join (f' - { x } ' for x in problem ['tags' ]) if len (problem ['tags' ]) > 0 else ''
80
+ tags = '\n ' + \
81
+ '\n ' .join (
82
+ f' - { x } ' for x in problem ['tags' ]) if len (problem ['tags' ]) > 0 else ''
56
83
lines .append (f"tags: { tags } " )
57
84
lines .append (f"done: false" )
58
85
lines .append (f"draft: false" )
@@ -63,23 +90,24 @@ def make_problem_yaml(problem: dict) -> str:
63
90
return '\n ' .join (lines )
64
91
65
92
66
- def get_problems (problems : list ) -> dict :
93
+ def get_problems (problems : list ) -> list :
67
94
"""문제 정보를 담고 있는 딕셔너리를 반환합니다.
68
95
"""
69
96
if len (problems ) < 1 :
70
97
raise ValueError ("Invalid number of problems" )
71
98
72
99
url = f"https://solved.ac/api/v3/problem/lookup?problemIds={ ',' .join (problems )} "
73
- response = requests .get (url )
100
+ response = urllib .request .urlopen (url )
101
+ source = response .read ()
74
102
75
- if response .status_code != 200 :
76
- raise Exception ("Unexpected response status" )
103
+ # if response.status_code != 200:
104
+ # raise Exception("Unexpected response status")
77
105
78
- json_data = response . json ( )
106
+ json_data = json . loads ( source )
79
107
problems = []
80
108
81
109
for problem in json_data :
82
- problem_info = {}
110
+ problem_info = defaultdict ( str )
83
111
problem_info ["id" ] = problem ["problemId" ]
84
112
problem_info ["name" ] = html .unescape (problem ["titleKo" ])
85
113
problem_info ["level" ] = problem ["level" ]
@@ -94,6 +122,7 @@ def get_problems(problems: list) -> dict:
94
122
95
123
return problems
96
124
125
+
97
126
# response = requests.get("https://solved.ac/api/v3/problem/show?problemId=1052")
98
127
# json_data = response.json()
99
128
@@ -106,6 +135,7 @@ def __init__(self):
106
135
help = "사용법 -p 1052 3023" , required = True , default = "" )
107
136
parser .add_argument (
108
137
"-o" , "--output" , help = "사용법: -o 문제 정보를 저장할 디렉터리" , required = False , default = "" )
138
+
109
139
parser .add_argument (
110
140
"-r" , "--random" , help = "사용법: -r [최소레벨] [최대레벨] 레벨 범위 안에서 문제를 랜덤으로 가져옵니다." , required = False , default = "" )
111
141
parser .add_argument (
@@ -138,13 +168,19 @@ def save_dir(self):
138
168
return self .__output
139
169
140
170
141
- if __name__ == '__main__' :
142
- app = CommandLineParser ()
143
-
171
+ def execute (app : CommandLineParser ) -> None :
144
172
if app .validation ():
145
173
problems = app .problems ()
146
174
save_dir = app .save_dir ()
147
175
176
+ # 입력받은 이름 폴더 ( abs path )
177
+ target_dir = os .path .join (os .getcwd (), save_dir )
178
+ if not os .path .isdir (target_dir ):
179
+ print (f"{ save_dir } 디렉터리가 존재하지 않습니다." )
180
+ return
181
+
182
+ print ("문제 정보를 생성합니다." )
183
+
148
184
problems_info = get_problems (problems )
149
185
150
186
writer = MarkdownTableWriter (
@@ -158,7 +194,22 @@ def save_dir(self):
158
194
159
195
print (writer .dumps ())
160
196
161
- if len (save_dir ) > 0 :
162
- for problem in problems_info :
163
- write_all_text (os .path .join (
164
- save_dir , f"{ problem ['id' ]} .md" ), make_problem_yaml (problem ))
197
+ for problem in problems_info :
198
+ content = make_problem_content (__template , problem )
199
+ problem_dir = os .path .join (
200
+ target_dir , f"[{ problem ['id' ]} ]{ problem ['name' ]} " )
201
+ if not os .path .isdir (problem_dir ):
202
+ os .mkdir (problem_dir )
203
+
204
+ write_all_text (os .path .join (
205
+ problem_dir , f"{ problem ['id' ]} .py" ), content )
206
+
207
+ write_all_text (os .path .join (
208
+ problem_dir , f"README.md" ), make_problem_yaml (problem ))
209
+
210
+ print (problems_info )
211
+
212
+
213
+ if __name__ == '__main__' :
214
+ app = CommandLineParser ()
215
+ execute (app )
0 commit comments