Work at SourceForge, help us to make it a better place! We have an immediate need for a Support Technician in our San Francisco or Denver office.

Close

Python, sort lines by strings length

Help
fb16
2012-10-19
2013-01-25
  • fb16
    fb16
    2012-10-19

    Hello,
    I don't know python. I've put together bits of code from the web to sort lines by the length of strings, i.e. to sort these lines:

    stri
    stri
    string
    string1
    string1
    s
    st
    str
    

    into these (removing duplicates also):

    string1
    string
    stri
    str
    st
    s
    

    Is there a way to streamline the following code i'm using, or maybe a simpler way to achieve the same result? Thanks

    editor.beginUndoAction()
    lines = {}
    if (editor.getSelText()):
        hm = editor.getSelText().splitlines()
        howmanyLines = len(hm)
    else:
        hm = editor.getLineCount()
        howmanyLines = hm
    for line in range(0, howmanyLines):
        strippedLine = editor.getLine(line).rstrip('\r\n ')
        if len(strippedLine) in lines:
            continue
        else:
            lines[len(strippedLine)]=[strippedLine]
    editor.clearAll()
    for l in reversed(sorted(lines)):
        console.write( "\r\n".join(reversed(sorted(lines[l]))) )
        print "\r\n".join(reversed(sorted(lines[l])))
    editor.endUndoAction()