在python中另一个文件的行中查找模式 [英] Find a pattern in the line of another file in python

查看:100
本文介绍了在python中另一个文件的行中查找模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm learning python so I have two files with a lot of lines:

文件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匹配的行第一列。我想要这样的文件名

I want print the lines where the pattern (number) file 1 matchs with the file 2 in the first column. I want an outfile like this

 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)
     

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

What I need to fix in it? Anybody can help me and support me? Thanks a lot

推荐答案

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))

另一个答案,其中每个键与各自的数据查找配对。我更改了您的输入,使用以下代码即可轻松理解。

Another answer where each key is paired with their respective data find. I've changed your inputs and you can easily understand using the below code.

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)

这篇关于在python中另一个文件的行中查找模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆