亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

python讀取文本文件內(nèi)容轉(zhuǎn)換為json格式的方法示例

 更新時(shí)間:2025年07月17日 10:16:08   作者:番茄番茄君  
在日常工作中我們經(jīng)常需要處理各種格式的數(shù)據(jù),有時(shí)候我們可能需要將一個(gè)文本文件中的內(nèi)容轉(zhuǎn)換為 JSON 格式的數(shù)據(jù),這篇文章主要介紹了python讀取文本文件內(nèi)容轉(zhuǎn)換為json格式的相關(guān)資料,需要的朋友可以參考下

前言

場(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)文章

最新評(píng)論