Hello all,
I managed to write the following script, to sort lines by their lengths. Since I know almost nothing about python, I'm pretty sure that it's not the better way to do that. Anyway, since it works for my purposes, I thought it could be useful also to others. Notice that it also removes duplicates. If you think it could be improved or you know a better way to do that, don't hesitate to post your solution here. Thank you, fb16
editor.beginUndoAction()
lista = {} # create a new dictionary
if editor.getSelText(): # grab the lines
linee = editor.getSelText().splitlines()
else:
linee = editor.getText().splitlines()
num = len(linee) # count them
for x in range( 0, num ): # for each line
linea = linee[x].rstrip('\r\n ') # remove spaces
if linea: # if not blank
if linea not in lista: # if not in the dictionary yet
lista[linea]=len(linea) # add it to the dictionary as "string: len(string)"
else: # otherwise...
continue # do nothing
else: #otherwise
continue # do nothing
editor.clearAll() # wipe lines in editor
for key, value in reversed(sorted(lista.items(), key=lambda (k,v): (v,k))): # for each key pair in the reversed/sorted dictionary
# print "%s: %s" % (key, value)
print(key) # print the key
editor.endUndoAction()
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
To deal also with special characters lengths, please change the line above:
lista[linea]=len(linea) # add it to the dictionary as "string: len(string)"
with this:
lista[linea]=len(linea.decode('utf-8')) # add it to the dictionary as "string: len(string)" (thanks for the decode hint to know the exact length of strings with special chars, to: http://webcache.googleusercontent.com/a/2247236)
fb16
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
Hello all,
I managed to write the following script, to sort lines by their lengths. Since I know almost nothing about python, I'm pretty sure that it's not the better way to do that. Anyway, since it works for my purposes, I thought it could be useful also to others. Notice that it also removes duplicates. If you think it could be improved or you know a better way to do that, don't hesitate to post your solution here. Thank you, fb16
To deal also with special characters lengths, please change the line above:
with this:
fb16
There's a lot of work here that isn't necessary. to sort a list of lines by length all you need is:
sorted_lines = sorted(list_of_lines, reverse=True, key=lambda x: len(x))
(maybe this wasn't available in 2012?)
I Love Python!!!