tags:

views:

90

answers:

3

When you're iterating over hundreds of lines in a file, what is the most (and least) efficient way to run regular expressions in Python?

Specifically, is the following bad form?

for line in file:
  data = re.search('(\d+\.\d+)\|(-\d+\.\d+)\|(.*?)\|(.*?)\|(\d+:\d+\s+\w+)\sTO\s(.*?)',line)
  one = data.group(1)
  two = data.group(2)
  three = data.group(3)
  four = data.group(4)
  five = data.group(5)
  six = data.group(6)
  # do the magic...
+3  A: 

Save the regex before the loop.

rx = re.compile( '(\d+\.\d+)\|(-\d+\.\d+)\|(.*?)\|(.*?)\|(\d+:\d+\s+\w+)\sTO\s(.*?)' )
for line in file:
  data = re.search(rx,line)
  one = data.group(1)
  two = data.group(2)
  three = data.group(3)
  four = data.group(4)
  five = data.group(5)
  six = data.group(6)
robert
I'd recommend using `data = rx.search(line)` instead of `data = re.search(rx,line)`.
JAB
Saving the regex is unnecessary. re caches compiled regexes, so you are only saving one dictionary lookup per iteration.
Ned Batchelder
@Ned: heh..that is news for me! :-) Python is really great!
jsbueno
@Ned: I believe it only caches a certain amount, though.
JAB
You can read the code in re.py: it caches 100 entries. The odd thing is when the cache reaches 100 entries, it simply clears the entire cache and starts over...
Ned Batchelder
+5  A: 

If you're just using this same regex over and over again, you don't need to compile it directly. http://docs.python.org/release/2.6.5/library/re.html#re.compile

The compiled versions of the most recent patterns passed to re.match(), re.search() or re.compile() are cached, so programs that use only a few regular expressions at a time needn’t worry about compiling regular expressions.

However, I would very much recommend not doing the assignments below that as you are. Try something like this:

for line in file:
    data = re.search('(\d+\.\d+)\|(-\d+\.\d+)\|(.*?)\|(.*?)\|(\d+:\d+\s+\w+)\sTO\s(.*?)',line)
    groups = data.groups()
    # do the magic...

MatchObject.groups() returns a tuple of all the groups in the match, with groups that don't participate in the match being assigned the value passed to groups() (said value defaults to None).

JAB
Or, if the variables are really needed: `one, two, three, four, five, six = data.groups()`
Jed Smith
This is great for my general Python learning. So thank you!But it's worth reporting that I've now experimented with all reported implementations and have seen little to no difference in performance.
Greg
@Greg: You're welcome.
JAB
+1  A: 

Unless the speed is an issue then you might want to just go with what you are comfortable reading, and which works.

Paddy3118