How to remove commas, brackets in python using regular expression?

后端 未结 2 1318
误落风尘
误落风尘 2021-01-24 22:25

These are the contents of my text file (eg:abc.doc):

{\'data\': [{\'name\': \'abc\'},{\'name\': \'xyz\'}]}

After opening the file in python; h

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-24 22:40

    Use ast.literal_eval() to turn it into a python structure, then print the values:

    with open(r'd:\output1.doc', 'r') as inputfile:
        inputstring = inputfile.read()
    
    data = ast.literal_eval(inputstring)
    for key, sublist in data.items():
        print '{}:'.format(key)
        for subdict in sublist:
            for key, value in subdict.items():
                print('{}:{}'.format(key, value))
    

    For your example that results in:

    >>> inputstring = "{'data': [{'name': 'abc'},{'name': 'xyz'}]}"
    >>> import ast
    >>> data = ast.literal_eval(inputstring)
    >>> for key, sublist in data.items():
    ...     print '{}:'.format(key)
    ...     for subdict in sublist:
    ...         for key, value in subdict.items():
    ...             print '{}:{}'.format(key, value)
    ... 
    data:
    name:abc
    name:xyz
    

    However: If you got this from the Facebook API, then you transcribed the format incorrectly. The Facebook API gives you JSON data, which uses double quotes (") instead:

    {"data": [{"name": "abc"},{"name": "xyz"}]}
    

    in which case you should use the json library that comes with Python:

    import json
    
    data = json.loads(inputstring)
    # process the same way as above.
    

    If you have a filename, you can ask the library to read straight from the file using:

    data = json.load(filename)  # note, no `s` after `load`.
    

提交回复
热议问题