如何识别字符串模式?

时间:2015-02-04 04:04:14

标签: python regex python-2.7 python-2.x

我想在python中对字符串进行分组,但我真的不知道如何处理这个问题。

假设我有一个文件名列表:

test-1.jpg
test-2.jpg
test-3.jpg
supertest-828.jpg
supertest-8429.jpg
5-mega-5435-test.jpg
5-mega-453-test.jpg
5-mega-325-test.jpg

现在我想通过他们的系列名称对它们进行分组。一个好的结果可能就是这样的一个词:

{"test-x.jpg":("test-1.jpg","test-2.jpg","test-3.jpg"), "supertest-x.jpg":(...), "5-mega-x-test.jpg":(...)}

现在我想知道解决这个问题的最佳方法是什么。我不想替换文件名中的所有数字。相反,我需要一种方法来找到正在改变的数字,并用“x”替换这个数字以获得该系列的标识符。

那么如何比较字符串并识别不相似的部分呢?

可能的洞穴加热是多个不断变化的数字,需要2个或更多“x”通配符和字符串中的静态数字,不应更改。

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

import re

def genericize(s):
    # replace one or more digits with an "x"
    return re.sub("\d+", "x", s)   

然后

>>> genericize("test-29.jpg")
'test-x.jpg'

您的整体计划

from collections import defaultdict

def group_fnames(lst):
    result = defaultdict(list)
    for fname in lst:
        result[genericize(fname)].append(fname)
    return result

然后

fnames = [
    'test-1.jpg',
    'test-2.jpg',
    'test-3.jpg',
    'supertest-828.jpg',
    'supertest-8429.jpg',
    '5-mega-5435-test.jpg',
    '5-mega-453-test.jpg',
    '5-mega-325-test.jpg'
]

print(group_fnames(fnames))

给出

{
    'supertest-x.jpg': ['supertest-828.jpg', 'supertest-8429.jpg'],
    'test-x.jpg': ['test-1.jpg', 'test-2.jpg', 'test-3.jpg'],
    'x-mega-x-test.jpg': ['5-mega-5435-test.jpg', '5-mega-453-test.jpg', '5-mega-325-test.jpg']
}