網(wǎng)站訪問速度檢測快速網(wǎng)站推廣
文章目錄
- 前言
- 一、TXT文件轉(zhuǎn)換為JSON數(shù)組
- 1.txt文件內(nèi)容
- 2.python代碼
- 3.輸出結(jié)果
- 二、TXT文件轉(zhuǎn)換為JSON對象
- 1.txt文件
- 2.python代碼
- 3.輸出結(jié)果
前言
場景:用于讀取包含空格分隔數(shù)據(jù)的TXT文件,并將其轉(zhuǎn)換為結(jié)構(gòu)化JSON文件
一、TXT文件轉(zhuǎn)換為JSON數(shù)組
1.txt文件內(nèi)容
地點A 116.405285 39.904989 43.5
地標B 121.473701 31.230416 4.2
觀測點C 113.264385 23.129112 12.8
2.python代碼
# -*- coding:utf-8 -*-
# @Time: 2025-02-25 20:25
# @Author: 番茄君
# @File:06-txt轉(zhuǎn)換JSON數(shù)組.py
# @Software: PyCharmimport jsondef txt_to_json(input_file, output_file):"""將TXT文件轉(zhuǎn)換為JSON格式:param input_file: 輸入文件路徑(如input.txt):param output_file: 輸出文件路徑(如output.json)"""# 定義一個列表data_list = []# 讀取文件并逐行處理with open(input_file, 'r', encoding='utf-8') as f:for line in f:# 去除首尾空白字符并按空格分割parts = line.strip().split(" ")# 驗證數(shù)據(jù)格式(需包含至少4列)if len(parts) >= 4:attribute = parts[0]try:# 提取經(jīng)度、緯度、高度并轉(zhuǎn)換為浮點數(shù)longitude = float(parts[1])latitude = float(parts[2])height = float(parts[3])# 構(gòu)建JSON對象data = {"屬性名": attribute,"經(jīng)度": longitude,"緯度": latitude,"高度": height}data_list.append(data)except ValueError:print(f"數(shù)據(jù)格式錯誤,跳過行:{line}")# 生成JSON文件with open(output_file, 'w', encoding='utf-8') as json_f:json.dump(data_list, json_f, ensure_ascii=False, indent=4)
3.輸出結(jié)果
[{"屬性名": "地點A","經(jīng)度": 116.405285,"緯度": 39.904989,"高度": 43.5},{"屬性名": "地標B","經(jīng)度": 121.473701,"緯度": 31.230416,"高度": 4.2},{"屬性名": "觀測點C","經(jīng)度": 113.264385,"緯度": 23.129112,"高度": 12.8}
]
二、TXT文件轉(zhuǎn)換為JSON對象
1.txt文件
地點A 116.405285 39.904989 43.5
地標B 121.473701 31.230416 4.2
觀測點C 113.264385 23.129112 12.8
2.python代碼
# -*- coding:utf-8 -*-
# @Time: 2025-02-25 16:15
# @Author: 番茄君
# @File:05-txt轉(zhuǎn)換為json對象.py
# @Software: PyCharmimport jsondef txt_to_json(input_file, output_file):"""將TXT文件轉(zhuǎn)換為嵌套JSON格式:param input_file: 輸入文件路徑(如input.txt):param output_file: 輸出文件路徑(如output.json)"""# 定義一個字典result = {}with open(input_file, 'r', encoding='utf-8') as f:for line_num, line in enumerate(f, 1):# 清理數(shù)據(jù)并分割列cleaned_line = line.strip()# print(line_num,line,cleaned_line)if not cleaned_line:continue # 跳過空行columns = cleaned_line.split()# 驗證數(shù)據(jù)格式if len(columns) != 4:print(f"第{line_num}行格式錯誤,需要4列數(shù)據(jù),實際列數(shù):{len(columns)}")continuekey = columns[0]try:# 提取并轉(zhuǎn)換坐標數(shù)據(jù)coordinates = {"經(jīng)度": float(columns[1]),"維度": float(columns[2]),"高度": float(columns[3])}except ValueError as e:print(f"第{line_num}行數(shù)值格式錯誤:{e}")continue# 檢查重復(fù)鍵if key in result:print(f"警告:鍵名'{key}'重復(fù)(第{line_num}行)")result[key] = coordinates# 生成JSON文件with open(output_file, 'w', encoding='utf-8') as json_file:json.dump(result, json_file, ensure_ascii=False, indent=2)# 使用示例
txt_to_json('input.txt', 'output.json')
3.輸出結(jié)果
{"地點A": {"經(jīng)度": 116.405285,"維度": 39.904989,"高度": 43.5},"地標B": {"經(jīng)度": 121.473701,"維度": 31.230416,"高度": 4.2},"觀測點C": {"經(jīng)度": 113.264385,"維度": 23.129112,"高度": 12.8}
}