Sort lines in a text file

John Machin sjmachin at lexicon.net
Sun Jul 22 02:04:56 EDT 2007


On Jul 22, 1:03 pm, leegold <goldt... at worldpost.com> wrote:
> say I have a text file:
>
> zz3 uaa4a ss 7 uu
>   zz 3 zzzz66 ppazz9
> aaaaaaaaa00000zz0
>
> I want to sort the text file. I want the key to be the number after
> the two "zz".  Or I guess a string of two zz then a number....So
> that's 3, 9, 0
>
> I'm trying to say that I want to sort lines in a file based on a
> regular expression. How could I do that in Python? I'm limited to
> Python 2.1, I can't add any 2nd party newer tools.

To save anybody who's tempted to write the whole shebang for you,
please specify which part(s) of the exercise you are having problems
with:
(a) reading lines from a file
(b) extracting a sort key from a line [presuming "number" means
"positive integer"; what do you want to do if multiple lines have the
same number? what if no number at all"]
(c) creating a list of tuples, where each tuple is (key,
line_contents)
(d) sorting the list
(e) creating the output file from the sorted list.





More information about the Python-list mailing list