kgrag/databaseconnect.py
2026-07-29 18:10:19 +08:00

46 lines
1.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import json
def find_ship_info(json_file_path, target_hull):
"""
从JSON文件中根据舷号查找舰船信息
:param json_file_path: JSON文件路径
:param target_hull: 目标舷号 (字符串或数字)
:return: 包含 model_name 和 ship_name 的字典,未找到返回 None
"""
try:
# 1. 打开并读取JSON文件
with open(json_file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
# 2. 遍历列表查找匹配项
# 注意:这里使用 str() 转换是为了兼容 JSON 中 hull_number 可能是数字(163)或字符串("163")的情况
for item in data:
if str(item.get('hull_number')) == str(target_hull):
return {
"model_name": item.get('model_name'),
"ship_name": item.get('ship_name')
}
# 如果遍历结束仍未找到
return None
except FileNotFoundError:
print(f"错误:找不到文件 {json_file_path}")
return None
except json.JSONDecodeError:
print("错误JSON 文件格式不正确")
return None
# --- 使用示例 ---
if __name__ == "__main__":
file_path = "E:\ZKYNLP\Hjunproject\project0506\kgrag\ship_xinghao.json" # 替换为你的实际文件名
search_hull = "163" # 你要查询的舷号
result = find_ship_info(file_path, search_hull)
if result:
print(f"查询成功!")
print(f"型号: {result['model_name']}")
print(f"舰名: {result['ship_name']}")
else:
print(f"未找到舷号为 {search_hull} 的记录")