| import json |
| import os |
|
|
| def show_conversation_slice(file_path, target_number, num_surrounding=3): |
| """ |
| Reads a JSON file (assumed to be a list of objects) and prints a specific item |
| and its surrounding items. |
| |
| Args: |
| file_path (str): The path to the JSON file. |
| target_number (int): The 1-based index of the item to find. |
| num_surrounding (int): The number of items to display before and after the target. |
| """ |
| |
| |
| target_index = target_number - 1 |
|
|
| |
| if not os.path.exists(file_path): |
| print(f"错误:文件不存在。请检查路径是否正确:\n{file_path}") |
| return |
|
|
| try: |
| |
| with open(file_path, 'r', encoding='utf-8') as f: |
| data = json.load(f) |
|
|
| |
| if not isinstance(data, list) or len(data) < target_index + 1: |
| print("错误:文件格式不正确或列表中的元素数量不足。") |
| return |
|
|
| |
| start_index = max(0, target_index - num_surrounding) |
| end_index = min(len(data), target_index + num_surrounding + 1) |
| |
| |
| conversations_slice = data[start_index:end_index] |
| |
| print(f"正在显示从第 {start_index + 1} 条到第 {end_index} 条,共 {len(conversations_slice)} 条对话。\n") |
| |
| |
| for i, conv in enumerate(conversations_slice): |
| current_index = start_index + i |
| |
| marker = "-->" if current_index == target_index else " " |
| print(f"{marker} 第 {current_index + 1} 条对话:") |
| |
| print(json.dumps(conv, indent=2, ensure_ascii=False)) |
| print("-" * 50) |
|
|
| except json.JSONDecodeError: |
| print(f"错误:文件 {file_path} 无法解析为有效的JSON格式。") |
| except Exception as e: |
| print(f"发生了一个意外错误:{e}") |
|
|
| |
| |
| file_path = "/root/test/weitiao/data_processing_hsichen/data_process_bq/data/delta_score_all_sharegpt_byclosure.json" |
|
|
| |
| target_conversation_number = 1173 |
|
|
| |
| if __name__ == "__main__": |
| show_conversation_slice(file_path, target_conversation_number) |