X Tutup
Skip to content

Commit 53cc1fa

Browse files
author
Ahmed Abdelaal
authored
Update sort.py
1 parent ebab050 commit 53cc1fa

File tree

1 file changed

+35
-3
lines changed

1 file changed

+35
-3
lines changed

sort.py

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,7 @@
1212
This could be extended by having nested blocks, sorting them recursively
1313
and flattening the end structure into a list of lines. Revision 2 maybe ^.^.
1414
"""
15-
16-
17-
def main():
15+
def sort_blocks():
1816
# First, we load the current README into memory
1917
with open('README.md', 'r') as read_me_file:
2018
read_me = read_me_file.read()
@@ -42,6 +40,40 @@ def main():
4240
with open('README.md', 'w+') as sorted_file:
4341
sorted_file.write(final_README)
4442

43+
def main():
44+
# First, we load the current README into memory as an array of lines
45+
with open('README.md', 'r') as read_me_file:
46+
read_me = read_me_file.readlines()
47+
48+
# Then we cluster the lines together as blocks
49+
# Each block represents a collection of lines that should be sorted
50+
# This was done by assuming only links ([...](...)) are meant to be sorted
51+
# Clustering is done by indentation
52+
blocks = []
53+
last_indent = None
54+
for line in read_me:
55+
s_line = line.lstrip()
56+
indent = len(line) - len(s_line)
57+
58+
if any([s_line.startswith(s) for s in ['* [', '- [']]):
59+
if indent == last_indent:
60+
blocks[-1].append(line)
61+
else:
62+
blocks.append([line])
63+
last_indent = indent
64+
else:
65+
blocks.append([line])
66+
last_indent = None
67+
68+
with open('README.md', 'w+') as sorted_file:
69+
# Then all of the blocks are sorted individually
70+
blocks = [''.join(sorted(block, key=lambda s: s.lower())) for block in blocks]
71+
# And the result is written back to README.md
72+
sorted_file.write(''.join(blocks))
73+
74+
# Then we call the sorting method
75+
sort_blocks()
76+
4577

4678
if __name__ == "__main__":
4779
main()

0 commit comments

Comments
 (0)
X Tutup