将.txt文件格式标签转成.json的python代码
时间: 2024-04-13 21:28:43 浏览: 15
下面是一个将 .txt 文件格式的标签转换为 .json 的示例 Python 代码:
```pythonimport json
def txt_to_json(txt_file_path, json_file_path):
with open(txt_file_path, 'r') as txt_file:
lines = txt_file.readlines()
data = []
for line in lines:
line = line.strip().split(' ')
label = line[0]
x_min, y_min, x_max, y_max = map(int, line[1:])
# 根据自己的需求构建 JSON 数据结构
instance = {
'label': label,
'bbox': {
'x_min': x_min,
'y_min': y_min,
'x_max': x_max,
'y_max': y_max
}
}
data.append(instance)
with open(json_file_path, 'w') as json_file:
json.dump(data, json_file)
# 调用示例
txt_file_path = 'labels.txt'
json_file_path = 'labels.json'
txt_to_json(txt_file_path, json_file_path)
```
上述代码中,`txt_to_json` 函数接受两个参数:`txt_file_path` 是输入的 .txt 文件路径,`json_file_path` 是输出的 .json 文件路径。函数首先读取 .txt 文件中的内容,然后解析每一行,并根据自己的需求构建 JSON 数据结构。最后,将构建好的数据写入到 .json 文件中。
你需要根据自己的具体需求修改代码中的数据结构和解析逻辑。确保在运行代码之前已经安装了 Python,并且将输入和输出路径替换为你自己的文件路径。