[英]How to recognize string patterns?
我想在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”通配符,並且字符串中的靜態數字不應更改。
謝謝您的幫助。
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']
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.