Python - Sorting in ascending order in a txt file

2024/7/6 22:24:10

I had a huge document that I parsed using regex to give a txt file (json.dump) similar to the following:

{"stuff": [{"name": ["frfer", "niddsi", ], "number": 11300, "identifier": "Tsdsad"}, {"name": ["Fast", "Guard", "Named", ], "number": 117900, "identifier": "Pdfms"}, {name: ["Fast", ], "number": 660, "identifier": "Unnamed"},    ]
}    

Now I would like to sort this document in ascending order based on the number. (i.e. "Pdfms" first, "Tsdsad" second, "Unnamed" third). I am unsure how to start this off in python, could anyone give me a point in the right direction? Thanks in advance

Answer

First problem: That's not legitimate JSON. You have extra commas (JSON doesn't like [a,b,c,]; it insists on [a,b,c]) in the source, and you have some identifiers (the third instance of name, e.g.) that are not quoted. Ideally, you will improve your initial text file parsing and JSONification to fix those issues. Or you can handle those fixups on the fly, like this:

json_source = """... your text data from above ...
"""import re
BADCOMMA = re.compile(r',\s+\]')
json_source = BADCOMMA.sub(']', json_source)BADIDENTIFIER = re.compile(r'\s+name:\s*')
json_source = BADIDENTIFIER.sub('"name":', json_source)

Beware, assuming you can fix every possible problem on the fly is a fragile pattern. Editing structured data files via regular expressions, likewise. Better to generate good JSON from the get-go.

Now, how to sort:

import json
data = json.loads(json_source)data['stuff'].sort(key=lambda item: item['number'], reverse=True)

That does an in-place sort of the "stuff" array, by the "number" value, and reverses it (because your example of how you want the output suggests a descending rather than the typical ascending sort).

To demonstrate that the sort has done what you want, the pprint module can be handy:

from pprint import pprint
pprint(data)

Yields:

{u'stuff': [{u'identifier': u'Pdfms',u'name': [u'Fast', u'Guard', u'Named'],u'number': 117900},{u'identifier': u'Tsdsad',u'name': [u'frfer', u'niddsi'],u'number': 11300},{u'identifier': u'Unnamed', u'name': [u'Fast'], u'number': 660}]}
https://en.xdnf.cn/q/120567.html

Related Q&A

How to make setuptools install a wheel containing multiple packages?

Suppose this wheel:M Filemode Length Date Time File - ---------- -------- ----------- -------- --------------------------------------------rw-rw-r-- 1358 26-Sep-2018 21:08…

Python - Randomly select words to display in a quiz [duplicate]

This question already has answers here:How can I randomly select (choose) an item from a list (get a random element)?(18 answers)Closed 9 years ago.Im in need of some help. Here we have my two lists:w…

How to extract only the english words from the list?

I tried to extract only the English words from the following list: l = [0, b, x14, x00, x1fP, xe0O, xd0, xea, i, x10, xa2, xd8, x08, x00, 00, x9d, x14, x00, x80, xcc, xbf, xb4, xdbLB, xb0, x7f, xe9, x9…

Javascript variable with html code regex email matching

This python script is not working to output the email address [email protected] for this case.This was my previous post.How can I use BeautifulSoup or Slimit on a site to output the email address from …

how to send a large array over tcp socket in python? is it possible to send? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 9 years ago.Improve…

Expand Python regex to list of all possible strings [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 5…

How can I group and sum a pandas dataframe? [duplicate]

This question already has answers here:How do I Pandas group-by to get sum?(11 answers)Closed 1 year ago.Ive had a good hunt for some time and cant find a solution so asking here. I have data like so:…

python add value to a list when iterate the list

values = [2,3,4] for v in values:values.append([v,255,255])Why do the statements above never end? I make a mistake in my code. However, I find it will never stop when I execute the code above.

resizing images from 64x64 to 224x224 for the VGG model

Can we resize an image from 64x64 to 256x256 without affecting the resolution is that a way to add zero on new row and column in the new resized output I m working on vgg and I get an error while addin…