Loop over the lines once, extracting any date, check if the date is in the set, if so increment the count using a Counter dict for the counts, at the end call Counter.most_common to get the 5 most common dates:
dates1 = {'21/5/2015', '4/4/2015', '15/6/2015', '30/1/2015', '19/3/2015', '25/2/2015', '25/5/2015', '8/2/2015', '6/6/2015', '15/3/2015', '15/1/2015', '30/5/2015'}
from collections import Counter
import re
def dates(data, dates1):
lines = data.split("\n")
dict_days = Counter()
r = re.compile("\d+/\d+/\d+")
for line in lines:
match = r.search(line)
if match:
dte = match.group()
if dte in dates1:
dict_days[dte] += 1
return dict_days.most_common(5)
This does a single pass over the list of lines as opposed to one pass for every dates in dates1.
For 100k lines with the date string at the end of a string with 200+ chars:
In [9]: from random import choice
In [10]: dates1 = {'21/5/2015', '4/4/2015', '15/6/2015', '30/1/2015', '19/3/2015', '25/2/2015', '25/5/2015', '8/2/2015', '6/6/2015', '15/3/2015', '15/1/2015', '30/5/2015'}
In [11]: dtes = list(dates1)
In [12]: s = "the same dates appear in a text ('data' from now on). It's a pretty long text. I want to loop over the text and get the number of times each date appear in the text, then i print the 5 dates with more occurances. "
In [13]: data = "\n".join([s+ choice(dtes) for _ in range(100000)])
In [14]: timeit dates(data,dates1)
1 loops, best of 3: 662 ms per loop
If more than one date can appear per line you can use findall:
def dates(data, dates1):
lines = data.split("\n")
r = re.compile("\d+/\d+/\d+")
dict_days = Counter(dt for line in lines
for dt in r.findall(line) if dt in dates1)
return dict_days.most_common(5)
If data is not actually a file like object and is a single string, just search the string itself:
def dates(data, dates1):
r = re.compile("\d+/\d+/\d+")
dict_days = Counter((dt for dt in r.findall(data) if dt in dates1))
return dict_days.most_common(5)
compiling the dates on the test data seems to be the fastest approach, splitting each substring is pretty close to the search implementation:
def dates_split(data, dates1):
lines = data.split("\n")
dict_days = Counter(dt for line in lines
for dt in line.split() if dt in dates1)
return dict_days.most_common(5)
def dates_comp_date1(data, dates1):
lines = data.split("\n")
r = re.compile("|".join(dates1))
dict_days = Counter(dt for line in lines for dt in r.findall(line))
return dict_days.most_common(5)
Using the functions above:
In [63]: timeit dates(data, dates1)
1 loops, best of 3: 640 ms per loop
In [64]: timeit dates_split(data, dates1)
1 loops, best of 3: 535 ms per loop
In [65]: timeit dates_comp_date1(data, dates1)
1 loops, best of 3: 368 ms per loop
if day in line:is dangerous, because ifday == '1/1/2015'it'll be in a line which is'21/1/2015'.if day in lineand surround the tokens with\bif they would occur as whole words.