Skip to content Skip to sidebar Skip to footer

Find A Pattern In The Line Of Another File In Python

I'm learning python so I have two files with a lot of lines: file 1 71528 1452 14587 file 2 country_hoj_17458 9 CA 5 CA 78.4 country_hoj_1452 10 CA 15 CA 96.5 count

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

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)

Post a Comment for "Find A Pattern In The Line Of Another File In Python"