简体   繁体   English

使用 Python 从 .txt 文件中创建 JSON

[英]Creating a JSON out of a .txt file using Python

This is what the data looks like in the txt file (tab delimited):这是 txt 文件中的数据(制表符分隔):

President, U.S. Vote For 1  0 of 1,599 precincts reporting
Candidate   Party   Votes
Deval Patrick   DEM 0
Bernie Sanders  DEM 0
Joseph R. Biden DEM 0
Michael R. Bloomberg    DEM 0
Elizabeth Warren    DEM 0
Pete Buttigieg  DEM 0
Tom Steyer  DEM 0
Andrew Yang DEM 0
Michael Bennet  DEM 0
John K. Delaney DEM 0
Tulsi Gabbard   DEM 0
Cory Booker DEM 0

This is the schema for the JSON I want to create:这是我要创建的 JSON 的架构:

"races": [ {   
        "name": "President, U.S.",
        "reference_id": "US-President",
        "election_date": "2020-03-17",
        "market": "balt",
        "state_postal": "MD",
        "reporting_units": [
            {
                "name": "US",
                "level": "fed",
                "state_postal": "MD",
                "precincts_reporting": 0,
                "total_precincts": 1599,
                "data_source_update_time": "2020-02-25T19:54:23+0000",
                "candidates": [
                    {
                        "last_name": "Patrick",
                        "middle_name":null,
                        "first_name":"Deval",  
                        "party": "DEM",
                        "vote_count": 0,
                    }, ...
                ]
            }
        ]
    }
 ]

So the candidates object would have to exist for each candidate, and there are many more races that are included in the txt file.因此,每个候选人都必须存在candidates对象,并且 txt 文件中包含更多races I know I'd use json.dumps for this but I'm really struggling with the syntax of how to address each row of this text file.我知道我会为此使用json.dumps ,但我真的在为如何解决这个文本文件的每一行的语法而苦苦挣扎。

If your source file is regular, you may want to consider parsing the file line-by-line to read it into python:如果您的源文件是常规文件,您可能需要考虑逐行解析文件以将其读入python:

with open(path_to_file, 'r') as f:
    # Loop through each line;
    # Separate logic for parsing 1st line and subsequent lines, 
    # along with any other cases you have to consider

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM