Easiest way to cross-reference a CSV file with a text file for common strings

I have a list of lines in a CSV file and another text file I would like to find for these lines. The CSV file only has the lines I'm interested in, but the text file contains a bunch of other text interspersed among the lines of interest (the lines I'm interested in are identification numbers for the squirrel database). What would be the easiest way to do this? I want to check a text file for every line in the CSV file. I work in a research lab at a top university, so you will be helping cutting edge research!

Thank:)

+1


source to share


1 answer


I would use Python for this. To print the corresponding lines, you can do this:



import csv
with open("strings.csv") as csvfile: 
    reader = csv.reader(csvfile)
    searchstrings = {row[0] for row in reader}   # Construct a set of keywords
with open("text.txt") as txtfile:
    for number, line in enumerate(txtfile):
        for needle in searchstrings:
            if needle in line: 
                print("Line {0}: {1}".format(number, line.strip()))
                break   # only necessary if there are several matches per line

      

+1


source







All Articles