背景:

我很清洁大(无法将保持在存储器)符分隔的文件。正如我清理输入文件,我建立了一个列表中的存储器;当它获得1,000,000项(约1GB在存储器)I类(使用默认的关键的下文),并编写的清单的文件。此类是把排序的文件一起回来。它的工作文件,我也遇到过这样远。我最大的情况下,迄今为止,合并66排的文件。

问题:

  1. 有孔在我的逻辑(其中它是脆弱的)?
  2. 我实施的合并排序 算法是否正确?
  3. 是否有任何明显的改进 可以吗?

例的数据:

这是一个抽象的行在这些文件:

'hash_of_SomeStringId\tSome String Id\t\t\twww.somelink.com\t\tOtherData\t\n'

外卖的是,我使用 'SomeStringId'.lower().replace(' ', '') 作为我的排序关键。

原始代码:

class SortedFileMerger():
    """ A one-time use object that merges any number of smaller sorted 
        files into one large sorted file.

        ARGS:
            paths - list of paths to sorted files
            output_path - string path to desired output file
            dedup - (boolean) remove lines with duplicate keys, default = True
            key - use to override sort key, default = "line.split('\t')[1].lower().replace(' ', '')"
                  will be prepended by "lambda line: ".  This should be the same 
                  key that was used to sort the files being merged!
    """
    def __init__(self, paths, output_path, dedup=True, key="line.split('\t')[1].lower().replace(' ', '')"):
        self.key = eval("lambda line: %s" % key)
        self.dedup = dedup
        self.handles = [open(path, 'r') for path in paths]
        # holds one line from each file
        self.lines = [file_handle.readline() for file_handle in self.handles]
        self.output_file = open(output_path, 'w')
        self.lines_written = 0
        self._mergeSortedFiles() #call the main method

    def __del__(self):
        """ Clean-up file handles.
        """
        for handle in self.handles:
            if not handle.closed:
                handle.close()
        if self.output_file and (not self.output_file.closed):
            self.output_file.close()

    def _mergeSortedFiles(self):
        """ Merge the small sorted files to 'self.output_file'. This can 
            and should only be called once.
            Called from __init__().
        """
        previous_comparable = ''
        min_line = self._getNextMin()
        while min_line:
            index = self.lines.index(min_line)
            comparable = self.key(min_line)
            if not self.dedup:                      
                #not removing duplicates
                self._writeLine(index)
            elif comparable != previous_comparable: 
                #removing duplicates and this isn't one
                self._writeLine(index)
            else:                                   
                #removing duplicates and this is one
                self._readNextLine(index)
            previous_comparable = comparable
            min_line = self._getNextMin()
        #finished merging
        self.output_file.close()

    def _getNextMin(self):
        """ Returns the next "smallest" line in sorted order.
            Returns None when there are no more values to get.
        """
        while '' in self.lines:
            index = self.lines.index('')
            if self._isLastLine(index):
                # file.readline() is returning '' because 
                # it has reached the end of a file.
                self._closeFile(index)
            else:
                # an empty line got mixed in
                self._readNextLine(index)
        if len(self.lines) == 0:
            return None
        return min(self.lines, key=self.key)

    def _writeLine(self, index):
        """ Write line to output file and update self.lines
        """
        self.output_file.write(self.lines[index])
        self.lines_written += 1
        self._readNextLine(index)

    def _readNextLine(self, index):
        """ Read the next line from handles[index] into lines[index]
        """
        self.lines[index] = self.handles[index].readline()

    def _closeFile(self, index):
        """ If there are no more lines to get in a file, it 
            needs to be closed and removed from 'self.handles'.
            It's entry in 'self.lines' also need to be removed.
        """
        handle = self.handles.pop(index)
        if not handle.closed:
            handle.close()
        # remove entry from self.lines to preserve order
        _ = self.lines.pop(index)

    def _isLastLine(self, index):
        """ Check that handles[index] is at the eof.
        """
        handle = self.handles[index]            
        if handle.tell() == os.path.getsize(handle.name):
            return True
        return False

编辑: 执行的建议 布赖恩 我想出了以下方案:

第二编辑: 新代码每 约翰*麦金's的建议:

def decorated_file(f, key):
    """ Yields an easily sortable tuple. 
    """
    for line in f:
        yield (key(line), line)

def standard_keyfunc(line):
    """ The standard key function in my application.
    """
    return line.split('\t', 2)[1].replace(' ', '').lower()

def mergeSortedFiles(paths, output_path, dedup=True, keyfunc=standard_keyfunc):
    """ Does the same thing SortedFileMerger class does. 
    """
    files = map(open, paths) #open defaults to mode='r'
    output_file = open(output_path, 'w')
    lines_written = 0
    previous_comparable = ''
    for line in heapq26.merge(*[decorated_file(f, keyfunc) for f in files]):
        comparable = line[0]
        if previous_comparable != comparable:
            output_file.write(line[1])
            lines_written += 1
        previous_comparable = comparable
    return lines_written

粗糙 测试

使用相同的输入文件(2.2GB的数据):

  • SortedFileMerger类51了 几分钟(3068.4秒)
  • 布赖恩's解决方案用了40分钟(2408.5秒)
  • 之后添加 约翰*麦金's的建议, 解码了36分钟 (2214.0秒)
有帮助吗?

解决方案

请注意,在python2.6,heapq有一个新的 合并 功能,这将为你做这个。

处理该定义关键功能,则可以仅包裹文件迭代的东西装饰它,使它比较的基础上的关键,并带它出去之后:

def decorated_file(f, key):
    for line in f: 
        yield (key(line), line)

filenames = ['file1.txt','file2.txt','file3.txt']
files = map(open, filenames)
outfile = open('merged.txt')

for line in heapq.merge(*[decorated_file(f, keyfunc) for f in files]):
    outfile.write(line[1])

[编辑] 即使在早期版本的蟒蛇,这可能是值得的,只需采取的执行情况的合并从以后heapq模块。这是纯粹的蟒蛇,并运行未经修改的在python2.5,因为它使用一堆获取下一个最低应该是非常有效时,合并大量的文件。

你应该能够简单复制的heapq.py 从python2.6安装、复制到你源作为"heapq26.py"并使用"from heapq26 import merge"-有没有2.6具体特征使用它。或者,你可以复制的合并的功能(重写heappop等呼吁参考的python2.5heapq模块)。

其他提示

<< 这个"答案"是一个评论的原始提问的结果代码>>

建议:eval()是咽和你在做什么限制的呼叫者使用lambda-关键取可能需要超过一个衬垫,并且在任何情况下,不需要同样的功能的初步排序步骤?

所以替代这样的:

def mergeSortedFiles(paths, output_path, dedup=True, key="line.split('\t')[1].lower().replace(' ', '')"):
    keyfunc = eval("lambda line: %s" % key)

与此:

def my_keyfunc(line):
    return line.split('\t', 2)[1].replace(' ', '').lower()
    # minor tweaks may speed it up a little

def mergeSortedFiles(paths, output_path, keyfunc, dedup=True):    
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top