|There's more than one way to do things|
Re: Best way to find patterns in csv file?by tmoertel (Chaplain)
|on Nov 30, 2004 at 23:54 UTC||Need Help??|
(Update: Added explanation of why this method is efficient.)
I would divide this problem into smaller pieces:
I might write the specifications like follows and stuff them into the __DATA__ section or a configuration file:
The first line says, "Pattern 1 requires that column 1 have the value 2, column 2 have the value 3, and column 0 have the value -1." The other lines read similarly. (There is no requirement for the values to be numbers. Any value that has a string representation will work in the following implementation.)
Next, I would write some code to convert the specs into an efficient internal representation. I might use the following representation, which has two parts:
The idea behind the representation is that we can decompose each pattern into a set of per-column patterns that must all be matched in order to satisfy the original pattern. For example, pattern 1 can be broken into three per-column patterns:
When scanning a line of the CSV file, if column 1 contains a 2, we can count it as a partial match toward pattern 1. If at the end of the line we have three such partial matches, we know we have satisfied all of pattern 1 and thus have a complete match.
What makes this process efficient is that our internal representation merges all of the shared per-column patterns. Thus when we encountered that value of 2 in column 1 earlier, we would instantly know to count it toward both pattern 1 and pattern 2. The only extra piece we need is to keep track of the counts for the current line in the CSV file, and we can do that via a tiny hash. Thus we can process the file line by line, in passing, with only a tiny bit of overhead.
In other words, this method ought to be fast, easy on the memory, and suitable for processing files larger than your hard drive.
The code to convert the specs into the above representation is short:
With the hard work done, we can now parse the CSV file (on STDIN) and look up matches against the internal representation:
Note that the inner-most loop almost always disappears because the hash lookup results in undef unless there is a match for the current column.
Let us try it out:
I hope that this helps.