简体   繁体   English

如何按字母顺序在Python中连接多个排序文件?

[英]how to join multiple sorted files in Python alphabetically?

How can I read multiple CSV input files line by line, compare the characters in each line, write the line appearing first alphabetically to an output file, and then advance the pointer of the minimum value's file to continue the comparisons with all files until the end of all input files is reached. 如何逐行读取多个CSV输入文件,比较每行中的字符,将第一行按字母顺序写入输出文件,然后前进最小值文件的指针,继续与所有文件进行比较,直到结束到达所有输入文件。 Here's some rough planning toward a solution. 这是一个针对解决方案的粗略计划。

buffer = []

for inFile in inFiles:

    f = open(inFile, "r")
    line = f.next()
    buffer.append([line, inFile])

#find minimum value in buffer alphabetically...
#write it to an output file...

#how do I advance one line in the file with the min value?
#and then continue the line-by-line comparisons in input files?

You can use heapq.merge : 你可以使用heapq.merge

import heapq
import contextlib

files = [open(fn) for fn in inFiles]
with contextlib.nested(*files):
    with open('output', 'w') as f:
        f.writelines(heapq.merge(*files))

In Python 3.x (3.3+): 在Python 3.x(3.3+)中:

import heapq
import contextlib

with contextlib.ExitStack() as stack:
    files = [stack.enter_context(open(fn)) for fn in inFiles]
    with open('output', 'w') as f:
        f.writelines(heapq.merge(*files))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在python中按字母顺序打印排序的多个句子? - how to print sorted multiple sentences alphabetically in python? 如何在 Python 中按键创建排序字典(按字母顺序) - How to create a sorted dictionary in Python by key (alphabetically) Python 3从已排序的大型文件中连接数据 - Python 3 join data from large files that are sorted 如何使用python连接多个选项卡文件 - how to join multiple tab files by using python 合并多个排序的大文件-Python - merge multiple sorted big files--python 如何在Python中使用xarray将多个netCDF文件中的数据连接起来? - How to join data from multiple netCDF files with xarray in Python? 如何在 Python 中按字母升序对列表中的多个字符串进行排序 - How to sort multiple strings inside list alphabetically ascending in Python Python - 使用递归 function 按字母排序顺序打印出 trie - Python - printing out a trie in alphabetically sorted order with a recursive function 自定义节点 Maya 中按字母顺序排序的属性 Python API 2.0 - Alphabetically sorted attributes in a custom node Maya Python API 2.0 Python:如何获取带有名称列表、两列格式的导入文本文件,并将它们放入按字母顺序排序的 Python 中? - Python: How do I take an imported text file with a list of names, two column format, and put them in python sorted alphabetically?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM