- 论坛徽章:
- 4
|
本帖最后由 mswsg 于 2016-04-29 10:40 编辑
先占楼,你起得这么早呢- python test.py --input1 dat1.txt --input2 dat2.txt > 2.out.txt
复制代码- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- __author__ = 'shengwei ma'
- __author_email__ = 'shengweima@icloud.com'
- import sys
- import getopt
- input_file1 = ""
- input_file2 = ""
- try:
- opts, args = getopt.getopt(sys.argv[1:], "h", ["input1=", "input2="])
- except getopt.GetoptError as err:
- print(str(err))
- for op, value in opts:
- if op == "--input1":
- input_file1 = value
- elif op == "--input2":
- input_file2 = value
- elif op == "-h":
- print("python get_value_according_first_column.py --input1 dat1 --input2 dat2 > out.txt")
- sys.exit()
- # 以上可忽略,定义shell中接受的参数及数据
- f1 = open(input_file1, 'r')
- f2 = open(input_file2, 'r')
- lines1 = f1.readlines() # 将整个文件读作一个列表,可以添加 print lines1 查看,这里一行表示里边的一个元素(字符串),如lines1[0],则表示第一行
- lines2 = f2.readlines() # 将整个文件读作一个列表,可以添加 print lines2 查看,第一行第一列,lines2[0][0]
- for line1 in lines1: # 遍历列表lines1中的每个元素,及遍历读取文件1的每一行
- line1 = line1.strip().split() # 这里的一行就是一个字符串,使用字符串的strip方法,去掉行尾换行符,使用split分割字符串成列表
- for line2 in lines2:
- line2 = line2.strip().split() # 同样 遍历文件2中每一行
- if line1[0] in line2: # line1[0] (注意是line 不是lines) 表示某一行的第一列,即查询某行第一列是否在文件2中,如果在
- line1.extend(line2[1:]) # 在的话,则将 文件2中的第二列以后的部分添加到第一行的后边
- print ' '.join(line1) # 将列表 line1 转换成字符串打印
- f1.close() # 关闭文件
- f2.close() # 关闭文件
复制代码 |
|