需要帮助格式化python字典字符串

时间:2017-10-24 18:06:36

标签: string python-2.7 dictionary

我无法将我下载的文件转换为字典对象,以便我可以访问每个元素。我认为密钥的引用缺失,这阻止我使用json_loads()等。你能帮我解决一下。我已经给出了下面的下载结果。我需要格式化它。

#include <stdio.h>
#include <string.h>

#define MAX_NAME 40
int main() {
    File * fpointer;
    char name[MAX_NAME+5];
    printf("Type name of program: ");
    scanf("%40s", name);
    strcat(name, ".txt");
    puts(name);
    return 0;
}

1 个答案:

答案 0 :(得分:0)

如果你有一个字典的字符串,这是一种方法。这有点hacky但应该运作良好。

import json
import re

regex_string = '(\w{1,}(?=:))'
regex = re.compile(regex_string, re.MULTILINE)
string = open('test_string', 'r').read() # I had the string in a file, but how
# just put the value here based on how you already had it stored.
string = regex.sub(r'"\1"', string)
python_object = json.loads(string)
# Now you can access the python_object just like any normal python dict.
print python_object["results"]

这是通过正则表达式之后的词典。现在你可以用json

阅读它
{
    "success": true,
    "results": 2,
    "rows": [{
        "Symbol": "LITL",
        "CompanyName": "LancoInfratechLimited",
        "ISIN": "INE785C01048",
        "Ind": "-",
        "Purpose": "Results",
        "BoardMeetingDate": "26-Sep-2017",
        "DisplayDate": "19-Sep-2017",
        "seqId": "102121067",
        "Details": "toconsiderandapprovetheUn-AuditedFinancialResultsoftheCompanyonstandalonebasisfortheQuarterendedJune30,2017."
    }, {
        "Symbol": "PETRONENGG",
        "CompanyName": "PetronEngineeringConstructionLimited",
        "ISIN": "INE742A01019",
        "Ind": "-",
        "Purpose": "Results",
        "BoardMeetingDate": "28-Sep-2017",
        "DisplayDate": "21-Sep-2017",
        "seqId": "102128225",
        "Details": "Toconsiderandapprove,interalia,theUnauditedFinancialResultsoftheCompanyforthequarterendedonJune30,2017."
    }]
}
相关问题