d-c*_*d-c 1 python sorting merge
基本上我有一堆包含域名的文件.我使用.sort(key = func_that_returns_tld)根据TLD对每个文件进行了排序
既然我已经完成了我想要合并所有文件并最终得到一个大规模的排序文件.我想我需要这样的东西:
open all files
read one line from each file into a list
sort list with .sort(key=func_that_returns_tld)
output that list to file
loop by reading next line
Run Code Online (Sandbox Code Playgroud)
我在考虑这个问题吗?任何关于如何实现这一点的建议将不胜感激.
如果你的文件不是很大,那么只需将它们全部读入内存(如S. Lott建议的那样).那绝对是最简单的.
但是,您提到校对会创建一个"大量"文件.如果它太大而不适合内存,那么也许使用heapq.merge.设置可能有点困难,但它的优点是不要求所有迭代都立即被拉入内存.
import heapq
import contextlib
class Domain(object):
def __init__(self,domain):
self.domain=domain
@property
def tld(self):
# Put your function for calculating TLD here
return self.domain.split('.',1)[0]
def __lt__(self,other):
return self.tld<=other.tld
def __str__(self):
return self.domain
class DomFile(file):
def next(self):
return Domain(file.next(self).strip())
filenames=('data1.txt','data2.txt')
with contextlib.nested(*(DomFile(filename,'r') for filename in filenames)) as fhs:
for elt in heapq.merge(*fhs):
print(elt)
Run Code Online (Sandbox Code Playgroud)
使用data1.txt:
google.com
stackoverflow.com
yahoo.com
Run Code Online (Sandbox Code Playgroud)
和data2.txt:
standards.freedesktop.org
www.imagemagick.org
Run Code Online (Sandbox Code Playgroud)
收益率:
google.com
stackoverflow.com
standards.freedesktop.org
www.imagemagick.org
yahoo.com
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2096 次 |
| 最近记录: |