【python实现】查找两个文件中有相同字符串的行

代码目的:两个文件,有些字符串是相同的,字符串的拆分是通过空格拆分的。我们希望在B文件中找到和A文件相同字符串的行。

用途:有一张成绩表,里面有姓名、学号,各项成绩等信息,然后我们有一个姓名列表,存放在文件A中,通过A我们可以找到对应姓名的信息。

''' search str in file,and print finded line in the file 
'''


def str_search_in_file(str, fname):
    with open(fname, 'r') as file_obj:
        while 1:
            line = file_obj.readline()
            if line:
                line = line.strip()
                if (line.find (str,0) >= 0):
                    print 'found = ',line
            else:
                break

def find_same_str_in_2file(file1,file2):
    with open(file1, 'r') as file_obj:
        list1 = file_obj.readlines()
        for line in list1:
            strlist = line.split(' ')
            i=0
            #print 'len=', len(strlist)
            while (i <len(strlist)):
                #print 'find for',strlist[i].strip() #strlist may have slash \n
                str_search_in_file(strlist[i].strip(), file2)
                i += 1

# file_reader('test.txt')
'''readline() each is oneline

'''
# file_read_use_while('test.txt')
str_search_in_file('lin', 'test.txt')
find_same_str_in_2file('test.txt', 'map.txt')

 

  • 4
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值