Gemini Enterprise를 사용하여 새 코드를 생성하고 기존 코드를 리팩터링할 수 있습니다.
프롬프트 예시
채팅 상자에 다음과 같은 프롬프트를 입력합니다.
Can you generate a Python function to parse a JSON file and extract specific
keys? Also, can you refactor the code in the attached file to improve its
readability and efficiency?
출력 예
이 프롬프트에 대한 응답으로 Gemini Enterprise는 다음과 유사한 출력을 생성합니다.
예. 두 가지 요청 모두 도와드릴 수 있습니다.
먼저 JSON 파일을 파싱하고 지정된 키 목록을 추출하는 범용 Python 함수가 있습니다. 여기에는 누락된 파일이나 잘못된 JSON 콘텐츠와 같은 일반적인 문제에 대한 오류 처리가 포함됩니다.
JSON 파싱 및 키 추출 함수
import json def extract_keys_from_json(file_path, keys_to_extract): """ Parses a JSON file and extracts values for a specific list of keys. Args: file_path (str): The path to the JSON file. keys_to_extract (list): A list of strings representing the keys to extract. Returns: dict: A dictionary containing the extracted keys and their values. Returns an empty dictionary if the file is not found or is invalid. """ extracted_data = {} try: with open(file_path, 'r') as f: data = json.load(f) # ...
리팩터링된 코드
제공해 주신
hi.py
파일의 리팩터링된 버전은 다음과 같습니다. 주요 개선사항은 깊이 중첩된if
문을 삭제하여 코드를 더 안전하고 읽기 쉽게 만드는 데 중점을 둡니다.이 버전에서는 존재하지 않을 수 있는 사전 키에 액세스하는 더 'Pythonic' 방식인
.get()
메서드를 사용합니다.KeyError
예외를 방지하고 코드를 더 평탄하게 만들어 따라가기 쉽습니다.import json def update_user_status_refactored(json_data): """ Parses user data, updates status, and handles nested keys safely. """ data = json.loads(json_data) # Safely get the email using .get() to avoid errors if keys are missing # .get('user', {}) returns an empty dict if 'user' is not found email = data.get('user', {}).get('details', {}).get('email') if email: print(f"Processing user: {email}") # Update the user status if 'user' in data: # ...