python讀取文本文件內(nèi)容轉(zhuǎn)換為json格式的方法示例
前言
場(chǎng)景:用于讀取包含空格分隔數(shù)據(jù)的TXT文件,并將其轉(zhuǎn)換為結(jié)構(gòu)化JSON文件
一、TXT文件轉(zhuǎn)換為JSON數(shù)組
1.txt文件內(nèi)容
地點(diǎn)A 116.405285 39.904989 43.5
地標(biāo)B 121.473701 31.230416 4.2
觀測(cè)點(diǎn)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: PyCharm
import json
def txt_to_json(input_file, output_file):
"""
將TXT文件轉(zhuǎn)換為JSON格式
:param input_file: 輸入文件路徑(如input.txt)
:param output_file: 輸出文件路徑(如output.json)
"""
# 定義一個(gè)列表
data_list = []
# 讀取文件并逐行處理
with open(input_file, 'r', encoding='utf-8') as f:
for line in f:
# 去除首尾空白字符并按空格分割
parts = line.strip().split(" ")
# 驗(yàn)證數(shù)據(jù)格式(需包含至少4列)
if len(parts) >= 4:
attribute = parts[0]
try:
# 提取經(jīng)度、緯度、高度并轉(zhuǎn)換為浮點(diǎn)數(shù)
longitude = float(parts[1])
latitude = float(parts[2])
height = float(parts[3])
# 構(gòu)建JSON對(duì)象
data = {
"屬性名": attribute,
"經(jīng)度": longitude,
"緯度": latitude,
"高度": height
}
data_list.append(data)
except ValueError:
print(f"數(shù)據(jù)格式錯(cuò)誤,跳過行:{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é)果
[
{
"屬性名": "地點(diǎn)A",
"經(jīng)度": 116.405285,
"緯度": 39.904989,
"高度": 43.5
},
{
"屬性名": "地標(biāo)B",
"經(jīng)度": 121.473701,
"緯度": 31.230416,
"高度": 4.2
},
{
"屬性名": "觀測(cè)點(diǎn)C",
"經(jīng)度": 113.264385,
"緯度": 23.129112,
"高度": 12.8
}
]
二、TXT文件轉(zhuǎn)換為JSON對(duì)象
1.txt文件
地點(diǎn)A 116.405285 39.904989 43.5
地標(biāo)B 121.473701 31.230416 4.2
觀測(cè)點(diǎn)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對(duì)象.py
# @Software: PyCharm
import json
def txt_to_json(input_file, output_file):
"""
將TXT文件轉(zhuǎn)換為嵌套JSON格式
:param input_file: 輸入文件路徑(如input.txt)
:param output_file: 輸出文件路徑(如output.json)
"""
# 定義一個(gè)字典
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()
# 驗(yàn)證數(shù)據(jù)格式
if len(columns) != 4:
print(f"第{line_num}行格式錯(cuò)誤,需要4列數(shù)據(jù),實(shí)際列數(shù):{len(columns)}")
continue
key = columns[0]
try:
# 提取并轉(zhuǎn)換坐標(biāo)數(shù)據(jù)
coordinates = {
"經(jīng)度": float(columns[1]),
"維度": float(columns[2]),
"高度": float(columns[3])
}
except ValueError as e:
print(f"第{line_num}行數(shù)值格式錯(cuò)誤:{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é)果
{
"地點(diǎn)A": {
"經(jīng)度": 116.405285,
"維度": 39.904989,
"高度": 43.5
},
"地標(biāo)B": {
"經(jīng)度": 121.473701,
"維度": 31.230416,
"高度": 4.2
},
"觀測(cè)點(diǎn)C": {
"經(jīng)度": 113.264385,
"維度": 23.129112,
"高度": 12.8
}
}
總結(jié)
到此這篇關(guān)于python讀取文本文件內(nèi)容轉(zhuǎn)換為json格式的文章就介紹到這了,更多相關(guān)python讀取文本文件內(nèi)容轉(zhuǎn)換json內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
學(xué)會(huì)python自動(dòng)收發(fā)郵件 代替你問候女友
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)自動(dòng)收發(fā)郵件,代替你問候女友,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-05-05
django admin.py 外鍵,反向查詢的實(shí)例
今天小編就為大家分享一篇django admin.py 外鍵,反向查詢的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-07-07
python+matplotlib繪制餅圖散點(diǎn)圖實(shí)例代碼
這篇文章主要介紹了python+matplotlib繪制餅圖散點(diǎn)圖實(shí)例代碼,本實(shí)例是官網(wǎng)的一個(gè)實(shí)例,不過也很簡(jiǎn)單,大家可以參考下2018-01-01
Python如何將兩個(gè)Excel文件按相同字段合并到一起
文章介紹了如何使用Pandas工具將兩個(gè)關(guān)聯(lián)的Excel文件合并成一個(gè),首先創(chuàng)建兩個(gè)Excel文件test1和test2,然后使用Pandas進(jìn)行合并,最后顯示新創(chuàng)建的Excel文件2025-02-02

