2508회 채점자료 업데이트
This commit is contained in:
78
script_utils.py
Normal file
78
script_utils.py
Normal file
@@ -0,0 +1,78 @@
|
||||
import os
|
||||
import json
|
||||
|
||||
def extract_and_format_scripts(project_data, output_directory="script_outputs"):
|
||||
"""
|
||||
읽어온 project_data에서 각 객체의 스크립트를 추출하여
|
||||
별도의 포맷팅된 JSON 파일로 저장합니다.
|
||||
|
||||
:param project_data: read_json을 통해 읽어온 딕셔너리 데이터
|
||||
:param output_directory: 결과 파일을 저장할 폴더 이름
|
||||
"""
|
||||
if not project_data:
|
||||
print("오류: 유효한 프로젝트 데이터가 없습니다.")
|
||||
return
|
||||
|
||||
# 결과물을 저장할 폴더 생성 (없으면)
|
||||
if not os.path.exists(output_directory):
|
||||
os.makedirs(output_directory)
|
||||
print(f"'{output_directory}' 폴더를 생성했습니다.")
|
||||
|
||||
objects_list = project_data.get("objects", [])
|
||||
|
||||
for obj in objects_list:
|
||||
object_name = obj.get("name")
|
||||
script_string = obj.get("script")
|
||||
|
||||
# 객체 이름과 스크립트 문자열이 모두 유효한 경우에만 처리
|
||||
if object_name and script_string:
|
||||
try:
|
||||
# 1. 스크립트 문자열을 파이썬 객체(리스트)로 파싱
|
||||
script_data = json.loads(script_string)
|
||||
|
||||
# 2. 저장할 파일 경로 설정
|
||||
file_name = f"{object_name}.json"
|
||||
output_path = os.path.join(output_directory, file_name)
|
||||
|
||||
# 3. 보기 좋은 형태의 JSON 파일로 저장
|
||||
with open(output_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(script_data, f, indent=2, ensure_ascii=False)
|
||||
|
||||
print(f"성공: '{output_path}' 파일이 생성되었습니다.")
|
||||
|
||||
except json.JSONDecodeError:
|
||||
print(f"주의: '{object_name}'의 스크립트는 비어있거나 파싱할 수 없어 건너뜁니다.")
|
||||
except Exception as e:
|
||||
print(f"오류: '{object_name}' 스크립트 처리 중 예외 발생 - {e}")
|
||||
|
||||
|
||||
def read_json(file_path):
|
||||
""" JSON 파일을 읽어 Python dict 로 반환 """
|
||||
if not os.path.exists(file_path):
|
||||
print(f"오류: 파일 '{file_path}' 을(를) 찾을 수 없습니다.")
|
||||
return None
|
||||
try:
|
||||
with open(file_path, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
except Exception as e:
|
||||
print(f"JSON 읽기 오류: {e}")
|
||||
return None
|
||||
|
||||
def main():
|
||||
# base_dir을 코드 내에서 직접 지정
|
||||
base_dir = r".\output\2508_CAS_2_B" # 원하는 최상위 디렉토리 경로로 수정하세요
|
||||
|
||||
# 하위 디렉토리 순회
|
||||
for root, dirs, files in os.walk(base_dir):
|
||||
if "project.json" in files:
|
||||
json_path = os.path.join(root, "project.json")
|
||||
output_directory = root # project.json이 있는 동일한 경로
|
||||
|
||||
print(f"▶ Processing: {json_path}")
|
||||
project_data = read_json(json_path)
|
||||
if project_data:
|
||||
extract_and_format_scripts(project_data, output_directory)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user