合并和排序两个已排序的文本文件

时间:2012-11-16 19:55:42

标签: python sorting text merge mergesort

我有两个文本文件:

样品r1.txt

Bud Abbott 51 92.3
Mary Boyd 52 91.4
Hillary Clinton 50 82.1

样品r2.txt

Don Adams 51 90.4
Jill Carney 53 76.3
Randy Newman 50 41.2

我想合并并使用姓氏进行排序,这是每行的第二个索引(程序可能不会使用任何预先存在的合并或排序软件)

这些是我的代码

one = open("sample-r1.txt",'r')
two = open("sample-r2.txt",'r')

for line in one:
    k = line.rstrip().split('\t')

for record in two:
    h= record.rstrip().split('\t')

i=0
j=0
newList=[]

while i < len(k) and j<len(h) :
    if k[i][1] <= h[j][1]:
        newList.append(k[i])
        i+=1            
    else:
        newList.append(h[j])
        j+=1

print(newList)

2 个答案:

答案 0 :(得分:0)

试试这个:几个修正:k,h.append而不是k,h =否则k和h是列表而k [] []是char而不是字符串

one = open("sample-r1.txt",'r')
two = open("sample-r2.txt",'r')
k=[]
h=[]
for line in one:
    tmp=line.rstrip().split('\t')
    if len(tmp)>1:
        k.append ( tmp )
for record in two:
    tmp=record.rstrip().split('\t')
    if len(tmp)>1:
        h.append ( tmp )
i=0
j=0
newList=[]
while i < len(k) and j < len(h):
    if k[i][1] <= h[j][1]:
        newList.append(k[i])
        i+=1
    else:
        newList.append(h[j])
        j+=1
while i < len(k):
    newList.append(k[i])
    i+=1
while j < len(h):
    newList.append(h[j])
    j+=1
for row in newList:
    print("\t".join(row))

答案 1 :(得分:0)

首先,不清楚您的输入是否以制表符分隔。使用split()代替split('\t'),以确保获得所有列。

当输入用尽时,你的while循环终止,但另一个输入仍然会剩下一些数据。由于产量太短,这应该是显而易见的。