Aaron Misquith
Aaron Misquith

Reputation: 621

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

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

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

After opening the file in python; how do i remove all the brackets, quotes and commas. The final output should be:

data:
name:abc
name:xyz             

Upvotes: 1

Views: 979

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1122062

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`.

Upvotes: 4

hd1
hd1

Reputation: 34657

Looks to me like you have json, which can be easily parsed using pyjson:

import json
obj=json.loads(u'''{'data': [{'name': 'abc'},{'name': 'xyz'}]}''')

Bob's your uncle now, innit?

Upvotes: 0

Related Questions