如何使用Python将文本转换为Json格式

时间:2017-09-27 06:13:43

标签: python json

我从下面的网站使用python Selenium提取数据。

https://portfoliomanager.energystar.gov/pm/targetFinder;jsessionid=F6FC40FBDE075BDA3834643F9BD65E37?execution=e1s2

请查看表"您的设计和/或目标的指标比较"

我已将表格解压缩为文字格式。

以下是

的示例输出
Metric Design Project Design Target Median Property*
ENERGY STAR score (1-100) Not Available 75 50
Source EUI (kBtu/ft²) 3.1 Not Available 127.9
Site EUI (kBtu/ft²) 1.0 Not Available 40.7
Source Energy Use (kBtu) 314.0 Not Available 12,793.0
Site Energy Use (kBtu) 100.0 Not Available 4,074.2
Energy Cost ($) 2,000.00 Not Available 81,484.00
Total GHG Emissions (Metric Tons CO2e) 0.0 Not Available 0.5

我试图将文本转换为json,

import csv
import json

with open('file.txt', 'rb') as csvfile:
    filereader = csv.reader(csvfile, delimiter=' ')
    i = 0
    header = []
    out_data = []
    for row in filereader:
        row = [elem for elem in row if elem]
        if i == 0:
            i += 1
            header = row
        else:
            row[0:4] = [row[0]+" "+row[1]+" "+row[2]+" "+row[3]]
            _dict = {}
            for elem, header_elem in zip(row, header):
                _dict[header_elem] = elem
            out_data.append(_dict)

print json.dumps(out_data)

我得到的JSON格式输出就像

[{"Project": "75", "Metric": "ENERGY STAR score (1-100)", "Design": "50"}]

JSON格式输出应采用

的形式
[{"Design Project": "Not Available", "Design Target": "75", "Metric": "ENERGY STAR score (1-100)", "Median Property*": "50"}]

1 个答案:

答案 0 :(得分:1)

  

你忘了为其他json键创建数据和标题(比如Design   项目,设计目标等)

这是正确的版本:

import csv
import json

with open('test.txt', 'r') as csvfile: # Opens file
    filereader = csv.reader(csvfile, delimiter=' ')
    i = 0
    header = []
    out_data = []
    for row in filereader:
        row = [elem for elem in row if elem]
        if i == 0:
            i += 2
            row[1:3] = [row[1]+" "+row[2]]  # Design Project key
            row[2:4] = [row[2]+" "+row[3]]  # Design Target key
            row[3:5] = [row[3]+" "+row[4]]  # Median Property*
            header = row
        else:
            row[0:4] = [row[0]+" "+row[1]+" "+row[2]+" "+row[3]]  # Metric value
            if len(row) == 5:  # check conditions for better parse
                row[1:3] = [row[1]+" "+row[2]]  # Design Project value
            _dict = {}
            for elem, header_elem in zip(row, header):
                _dict[header_elem] = elem
            out_data.append(_dict)

    print json.dumps(out_data)

仅当数据结构不变且键/值由相同数量的单词组成时才有效。

您可以添加其他条件(例如第21行中的我):

if len(row) == 5:  # check conditions for better parse
    row[1:3] = [row[1]+" "+row[2]]  # Design Project value