文本文件比对

#!/usr/local/python27/bin/python2.7
#coding:utf-8
__author__ = 'similarface'
import os,sys
from pandas import *
import pandas as pd
if sys.argv.__len__()<6:
    info='''
---------------------------------------------------------------------------
该程序比对2个文件的列,如果文件1的列=文件2的列,则输出,输出为csv格式文件!
使用方法:merge 文件1 比对列1 文件2 比对列2 输出文件
useage:merge file1 comparecol file2 comparecol outfile
备注:文件的列从1开始计数,可以在后面追加debug。
---------------------------------------------------------------------------
    '''
    print(info)
    print('使用方法:merge file1 comparecol file2 comparecol outfile')
    print(sys.argv)
    sys.exit(-1)
else:
    infile1=sys.argv[1]
    comparepos1=sys.argv[2]
    infile2=sys.argv[3]
    comparepos2=sys.argv[4]
    outputfile=sys.argv[5]
    flag=True
    try:
        debug=sys.argv[6]
        if debug!='debug':
            flag=False
    except IndexError:
        flag=False
    if os.path.exists(infile1) and os.path.exists(infile2) and os.path.isfile(infile2) and os.path.isfile(infile1):
        if infile1.endswith('csv'):
            data1=pd.read_table(infile1,header=None,sep=',')
        else:
            data1=pd.read_table(infile1,header=None,sep='s+')

        if infile2.endswith('csv'):
            data2=pd.read_table(infile2,header=None,sep=',')
        elif infile2.endswith('txt'):
            data2=pd.read_table(infile2,header=None)
        else:
            data2=pd.read_table(infile2,header=None,sep='s+')
        if flag:
            print('索引上+1就是比对的参数值')
            print('------data1数据源------')
            print(data1.columns)
            print(data1.ix[0:10])
            print('------data2数据源------')
            print(data2.columns)
            print(data2.ix[0:10])

        r=pd.merge(data1,data2,left_on=int(comparepos1)-1,right_on=int(comparepos2)-1)
        r.to_csv(outputfile)
        if flag:
            print(pd.read_csv(outputfile,nrows=10))
    else:
        print('给定文件文件不存在!')
/shell/merge.sh 2.txt 1 3.txt 1 result.csv debug
索引上+1就是比对的参数值
------data1数据源------
Int64Index([0], dtype='int64')
                0
0   111-1116-3782
1   111-1120-5765
2   111-1114-6846
3   111-1121-1087
4   111-1120-3655
5   111-1113-2658
6   111-1115-5084
7   111-1117-2234
8   111-1112-2871
9   111-1119-4502
10  111-1112-4707
------data2数据源------
Int64Index([0], dtype='int64')
                0
0   111-1127-3269
1   111-1123-1863
2   111-1125-5555
3   111-1129-1959
4   111-1125-5081
5   111-1122-3431
6   111-1127-0824
7   111-1126-2713
8   111-1128-8409
9   111-1121-3852
10  111-1121-8611
   Unnamed: 0              0
0           0  111-1116-3782
原文地址:https://www.cnblogs.com/similarface/p/5500473.html