【问题标题】:Find a pattern in the line of another file in python [closed]在python中的另一个文件的行中查找模式[关闭]
【发布时间】:2020-10-05 23:27:11
【问题描述】:

我正在学习 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)
     

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

【问题讨论】:

  • 你需要重复你的关于字符串处理的教程材料。学习使用in 运算符。 Stack Overflow 无意取代现有的教程材料。

标签: python database loops file pattern-matching


【解决方案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 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-14
    • 2013-10-04
    • 2013-02-09
    • 1970-01-01
    • 2017-04-20
    • 1970-01-01
    • 2021-12-22
    • 2021-12-19
    相关资源
    最近更新 更多