2

ファイルの膨大なリスト (20k) があります。各ファイルには、最初の行に一意の識別子文字列があります。この最初の行には、この識別子文字列のみが含まれています。ファイルのリストには約n異なる識別子があり、各識別子には少なくとも 500 個のファイルがあります (ただし、各識別子のファイルの量は等しくありません)。

(各識別子の) 500 個のファイルをランダムにサンプリングし、それらを別のディレクトリにコピーして、元のリストのサブセットになり、各識別子が同じ量のファイルで表されるようにする必要があります。

のランダムなリストを提供できることはわかっrandom.sample()ていますが、それは最初の行の制約を処理せず、shutil.copy()ファイルをコピーできます...

しかし、ファイルの最初の行にある識別子の制約に従うことで、Python でこれを (効率的に) 行うにはどうすればよいでしょうか?

4

1 に答える 1

3

あなたが説明したことから、すべてのファイルの最初の行を読んで、それらを識別子で整理する必要があります。このようなものは、あなたが探していることをすると思います:

import os
import collections
import random
import shutil

def get_identifier(path):
    with open(path) as fd:
        return fd.readline().strip()       #assuming you don't want the \n in the identifier

paths = ['/home/file1', '/home/file2', '/home/file3']
destination_dir = '/tmp'
identifiers = collections.defaultdict(list)
for path in paths:
    identifier = get_identifier(path)
    identifiers[identifier].append(path)

for identifier, paths in identifiers.items():
    sample = random.sample(paths, 500)
    for path in sample:
        file_name = os.path.basename(path)
        destination = os.path.join(destination_dir, file_name)
        shutil.copy(path, destination)
于 2013-06-09T13:52:47.173 に答える