您是否能够一次保存 1000 个文件是一个单独的问题,取决于您的操作系统及其配置;如果没有,您必须分两步进行 - 将 N 个文件组合并到临时文件中,然后将临时文件合并到最终结果文件中(两个步骤就足够了,因为它们可以让您合并总共 N 个平方文件;只要 N 至少为 32,因此应该可以合并 1000 个文件)。在任何情况下,这都是与“将 N 个输入文件合并到一个输出文件”任务不同的问题(只是您是调用该函数一次还是重复调用该函数的问题)。
该函数的总体思路是保留一个优先级队列(模块heapq 擅长于此;-)包含“排序键”(在您的情况下为当前 TLD)的小列表,然后是最后一行从文件中读取,最后打开的文件准备好读取下一行(并且在两者之间有一些不同的东西,以确保正常的字典顺序不会意外地尝试比较两个打开的文件,这会失败)。我认为一些代码可能是解释一般想法的最佳方式,所以接下来我将编辑这个答案以提供代码(但是我没有时间 test 它,所以把它当作伪代码交流想法;-)。
import heapq
def merge(inputfiles, outputfile, key):
"""inputfiles: list of input, sorted files open for reading.
outputfile: output file open for writing.
key: callable supplying the "key" to use for each line.
"""
# prepare the heap: items are lists with [thekey, k, theline, thefile]
# where k is an arbitrary int guaranteed to be different for all items,
# theline is the last line read from thefile and not yet written out,
# (guaranteed to be a non-empty string), thekey is key(theline), and
# thefile is the open file
h = [(k, i.readline(), i) for k, i in enumerate(inputfiles)]
h = [[key(s), k, s, i] for k, s, i in h if s]
heapq.heapify(h)
while h:
# get and output the lowest available item (==available item w/lowest key)
item = heapq.heappop(h)
outputfile.write(item[2])
# replenish the item with the _next_ line from its file (if any)
item[2] = item[3].readline()
if not item[2]: continue # don't reinsert finished files
# compute the key, and re-insert the item appropriately
item[0] = key(item[2])
heapq.heappush(h, item)
当然,在您的情况下,作为key 函数,您将需要一个提取顶级域的函数,给定一行是域名(带有尾随换行符) - 在上一个问题中您已经指出为此目的,将 urlparse 模块比字符串操作更可取。如果你坚持字符串操作,
def tld(domain):
return domain.rsplit('.', 1)[-1].strip()
或类似的东西在这种约束下可能是一种合理的方法。
如果您使用 Python 2.6 或更高版本,heapq.merge 是显而易见的替代方案,但在这种情况下,您需要自己准备迭代器(包括确保“打开的文件对象”永远不会被意外比较...)使用与我在上面更可移植的代码中使用的类似的“装饰/取消装饰”方法。