data_process_bq / script /show_conversation.py
bingqin111's picture
Upload folder using huggingface_hub
3d27cfe verified
Raw
History Blame Contribute Delete
2.69 kB
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.
"""
# 将1-based的索引转换为0-based的列表索引
target_index = target_number - 1
# 检查文件是否存在
if not os.path.exists(file_path):
print(f"错误:文件不存在。请检查路径是否正确:\n{file_path}")
return
try:
# 打开并加载JSON文件
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
# 使用箭头标记出第3740条对话
marker = "-->" if current_index == target_index else " "
print(f"{marker}{current_index + 1} 条对话:")
# 使用 json.dumps 格式化输出,使其更易读
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"
# 要查找的对话序号(1-based)
target_conversation_number = 1173
# --- 运行脚本 ---
if __name__ == "__main__":
show_conversation_slice(file_path, target_conversation_number)