在 python 中的另一个文件的行中查找模式

我正在学习 python,所以我有两个包含很多行的文件:


文件1


71528

1452

14587

文件2


country_hoj_17458   9  CA   5    CA 78.4

country_hoj_1452   10  CA   15   CA 96.5

country_hoj_14787  19  CA   51   CA 12.4

country_hoj_15742  19  CA   51   CA 12.4

country_hoj_171528  19  CA   51   CA 12.4

我想打印第一列中模式(数字)文件 1 与文件 2 匹配的行。我想要一个这样的输出文件


 country_hoj_1452   10  CA   15   CA 96.5

 country_hoj_14787  19  CA   51   CA 12.4

我的脚本是这样的:


filename = numbers.txt

filename2 = data.txt

with open(filename) as f:

    with open (filename2) as m:

        for line in f:

                if line in m:

                       print (m)

     

我需要修复什么?有人可以帮助我并支持我吗?多谢


慕运维8079593
浏览 89回答 1
1回答

慕仙森

filename = 'numbers.txt'filename2 = 'data.txt'with open(filename) as numberLines:    with open (filename2) as dataLines:        nL = numberLines.read().splitlines()        dL = dataLines.read().splitlines()        dataReadLines = [j for i in nL for j in dL if i in j]        #dataReadLines = [i for i in nL]        print (str(dataReadLines))另一个答案是每个密钥都与其各自的数据配对。我已经更改了您的输入,您可以使用以下代码轻松理解。from collections import defaultdictfilename = 'numbers.txt'filename2 = 'data.txt'with open(filename) as numberLines:    with open (filename2) as dataLines:        nL = numberLines.read().splitlines()        dL = dataLines.read().splitlines()        defDList = defaultdict(list)        dataReadLines = [defDList[i].append(j) for i in nL for j in dL if i in j]        #dataReadLines = [i for i in nL]        print (defDList)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python