2017-10-13 12 views
0

私はさまざまなサイズの2000個の.txtファイルを含むディレクトリを持っています。Pythonグループの類似したファイル名

trend_micro.txt 
trendmicro.txt 

microsoft-windows.txt 
microsoft.txt 

私は、リスト内のすべてのファイル名を持っています。そのうちのいくつかは、次のような非常に類似した名前を、持っています。これらの類似したファイル名を一緒にグループ化するにはどうすればいいですか?

答えて

1

「類似」と「違う」の定義方法は明確ではありません。ここでは、2つのファイル名が似ていると仮定します。 " - "と "_"を取り除いた後で同じになるとします。

def reduce_key(fn): 
    # you can change this according to your definition of "similar" 
    return fn.replace("-","").replace("_","") 

from collections import defaultdict 
# this holds the grouped filenames 
group_dict = defaultdict(list) 
for fn in your_list: 
    key = reduce_key(fn) 
    group_dict[key].append(fn) 

print(group_dict) 
関連する問題