使用场景:生成和重构代码

您可以使用 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:
        # ...