如何使用python根据该行中的特定模式对行进行排序

时间:2014-09-18 05:28:07

标签: python sorting

我在文件中有这样的行

1)  /^void UART0_ErrInterrupt(void)$/;" kind:function line:1367 signature:(void)
2)  /^tUI8 UART0_Get_TIE_Flag( void )$/;" kind:function line:211 signature:( void )
3)  /^tUI8 UART1_Get_TIE_Flag( void )$/;" kind:function line:281 signature:( void )

我需要使用python对这些行进行排序。我需要根据行后数量进行排序:在每一行中。例如,在上面的行中,行的顺序应该是2),3),1)按升序排列。我该怎么做?

2 个答案:

答案 0 :(得分:1)

sorted与自定义键

一起使用
>>> import re
>>> with open('file.txt') as f:
...     lines = sorted(f, key=lambda line: int(re.search(r"(?<=line:)\d+", line).group()))

>>> for l in lines:
...     print l

2)  /^tUI8 UART0_Get_TIE_Flag( void )$/;" kind:function line:211 signature:( void )

3)  /^tUI8 UART1_Get_TIE_Flag( void )$/;" kind:function line:281 signature:( void )

1)  /^void UART0_ErrInterrupt(void)$/;" kind:function line:1367 signature:(void)

答案 1 :(得分:0)

您可以定义一个解释如何进行排序的函数:

def sortkey(line):
    # find the number after the first "line:" and convert it to an integer
    return int(re.search(r"(?<=line:)\d+", line).group())

并将该函数传递给排序函数/方法:

>>> sorted(lines, key=sortkey)
['2)  /^tUI8 UART0_Get_TIE_Flag( void )$/;" kind:function line:211 signature:( void )', 
 '3)  /^tUI8 UART1_Get_TIE_Flag( void )$/;" kind:function line:281 signature:( void )', 
 '1)  /^void UART0_ErrInterrupt(void)$/;" kind:function line:1367 signature:(void)']