我在文件中有这样的行
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)按升序排列。我该怎么做?
答案 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)']