为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕运维8079593 2023-10-11 16:08:16
我正在学习 python,所以我有两个包含很多行的文件:文件171528145214587文件2country_hoj_17458   9  CA   5    CA 78.4country_hoj_1452   10  CA   15   CA 96.5country_hoj_14787  19  CA   51   CA 12.4country_hoj_15742  19  CA   51   CA 12.4country_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.txtfilename2 = data.txtwith open(filename) as f:    with open (filename2) as m:        for line in f:                if line in m:                       print (m)     我需要修复什么?有人可以帮助我并支持我吗?多谢
查看完整描述

1 回答

?
慕仙森

TA贡献1827条经验 获得超7个赞

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 defaultdict


filename = '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)


查看完整回答
反对 回复 2023-10-11
  • 1 回答
  • 0 关注
  • 56 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信