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 は次のような出力を生成します。
承知しました。ご依頼の 2 つの内容どちらにも対応できます。
まず、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: # ...