用途:生成及重構程式碼

您可以使用 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 陳述式,讓程式碼更安全且更容易閱讀。

這個版本使用 .get() 方法,這是存取可能不存在的字典鍵時,更符合 Python 風格的做法。這有助於避免 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:
        # ...