【问题标题】:Convert TXT/CSV to JSON in Python 3在 Python 3 中将 TXT/CSV 转换为 JSON
【发布时间】:2020-08-03 20:33:18
【问题描述】:

我需要帮助将所有行从简单的 .txt 文件转换为 JSON。我正在尝试使用 pandas 库将 .txt 转换为 .csv,然后将 .csv 转换为 JSON。但是,我无法从输出 JSON 中的原始 .txt 文件中捕获所有行。

这是文件(data.txt),逐行列出:

Images
Median of 100 points per image
Dataset
76 out of 77 images calibrated (98%), all images enabled
Camera Optimization
0.60% difference in initial and optimized camera parameters
Matches
Median of 1000 matches per image
Georeferencing
Yes, 3D GCP

这是我试图用来将 .txt 转换为 .csv 的代码:

import csv

with open('C:\\Users\\mdl518\\Desktop\\image_metadata.txt', 'r') as in_file:
    stripped = (line.strip() for line in in_file)
    lines = (line.split(",") for line in stripped if line)
    with open('C:\\Users\\mdl518\\Desktop\\image_metadata.csv', 'w') as out_file:
        writer = csv.writer(out_file)
        writer.writerows(lines) 

我必须注意,文本以逗号 (,) 分隔的行列在 .csv 中的两个单独单元格中,但是当我尝试将 CSV 写入 JSON 时,这些特定行会从 JSON 文件中省略。这是我用来尝试从 .csv 转换为 JSON 的代码。

import pandas as pd

df=pd.read_csv("C:\\Users\\mdl518\\Desktop\\image_metadata.csv", header=None, error_bad_lines=False, encoding='utf-8')
df.to_json("C:\\Users\\mdl518\\Desktop\\image_metadata.json", orient="table")

对于输出 JSON,我并不太关心索引名称(甚至 n0、n1 等标签都是可以接受的)——我只需要能够用逗号捕获 .txt/.csv 的行分离输出 JSON 中的文本,非常感谢任何帮助!

【问题讨论】:

    标签: pandas csv encoding automation missing-data


    【解决方案1】:

    我为您的输入文件结构编写了一个脚本,将内容存储在字典中,并将字典写入 JSON 文件:

    with open('untitled.txt') as file_handle:
        file_content = file_handle.read()
    
    my_dict = {}
    for line in file_content.split('\n'):
        if line.startswith('Median') and ("points per image" in line):
            print('median points per image:',line.split(' ')[2])
            my_dict['median points per image:'] = line.split(' ')[2]
        elif "images calibrated" in line:
            print('lower:',line.split(' ')[0]) 
            my_dict['lower:'] = line.split(' ')[0]
            print('total:',line.split(' ')[3])
            my_dict['total:'] = line.split(' ')[3]
            print('percentage:',line.split(' ')[6].replace('(','').replace('%)',''))
            my_dict['percentage:'] = line.split(' ')[6].replace('(','').replace('%)','')
        elif "difference in" in line:
            print('difference:',line.split(' ')[0])
            my_dict['difference:'] = line.split(' ')[0]
        elif line.startswith("Median") and "matches per image" in line:
            print('median matches per image:',line.split(' ')[2])
            my_dict['median matches per image:'] = line.split(' ')[2]
            
    import json
    with open("sample.json", "w") as outfile:  
        json.dump(my_dict, outfile) 
    

    我保留了打印语句,以便您可以在创建字典时看到正在加载的内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-03
      • 1970-01-01
      • 2017-01-31
      • 1970-01-01
      • 2021-06-05
      • 2016-09-21
      • 2015-08-07
      • 1970-01-01
      相关资源
      最近更新 更多