本文介绍了根据正则表达式匹配对字符串列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,看起来像:

I have a text file that looks a bit like:

random text random text, can be anything blabla %A blabla
random text random text, can be anything blabla %D blabla
random text random text, can be anything blabla blabla %F
random text random text, can be anything blabla blabla
random text random text, %C can be anything blabla blabla

当我输入readlines()时,它变成一个句子列表.现在,我希望此列表按%之后的字母排序.因此,基本上,将排序应用于上面的内容时,应该看起来像这样:

When I readlines() it in, it becomes a list of sentences. Now I want this list to be sorted by the letter after the %. So basically, when the sort is applied to the above, it should look like:

random text random text, can be anything blabla %A blabla
random text random text, %C can be anything blabla blabla
random text random text, can be anything blabla %D blabla
random text random text, can be anything blabla blabla %F
random text random text, can be anything blabla blabla

是否有一个好方法,或者我必须将每个字符串分成小管,然后将字母移动到特定列,然后使用key=operator.itemgetter(col)进行排序?

Is there a good way to do this, or will I have to break each string in to tubles, and then move the letters to a specific column, and then sort using key=operator.itemgetter(col)?

谢谢

推荐答案

In [1]: def grp(pat, txt):
   ...:     r = re.search(pat, txt)
   ...:     return r.group(0) if r else '&'

In [2]: y
Out[2]:
['random text random text, can be anything blabla %A blabla',
 'random text random text, can be anything blabla %D blabla',
 'random text random text, can be anything blabla blabla %F',
 'random text random text, can be anything blabla blabla',
 'random text random text, %C can be anything blabla blabla']

In [3]: y.sort(key=lambda l: grp("%\w", l))

In [4]: y
Out[4]:
['random text random text, can be anything blabla %A blabla',
 'random text random text, %C can be anything blabla blabla',
 'random text random text, can be anything blabla %D blabla',
 'random text random text, can be anything blabla blabla %F',
 'random text random text, can be anything blabla blabla']

这篇关于根据正则表达式匹配对字符串列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 13:34