#!/bin/env python # Using generator comprehension on the 'test_regexp.py' regular expression examples import sys import fileinput import re import string # print all lines with 'read' event types file='sample_100k_lines.json' print ("Reading from ", file) # ----------------------------------------------------------------------------- # functional version with open(file,"r") as f: xs = (line for line in f if re.search('"event_type":"read"', line)) # print the results and count matches n = 0 for l in xs: n+=1 # print(l) print("Found " + str(n) + " matches") # NB: since xs is a generator as well, you can't directly ask for its length try: print("Found " + len(c) + " matches in total") except: print("Error in finding length of a generator comprehension") # NB: this only works, if xs has been expanded before this point for l in xs: print(l) # ----------------------------------------------------------------------------- # imperative version def proc_file(file): """Find read events in an issuu log file.""" f = open(file,"r") for line in f: if re.search('"event_type":"read"', line): yield line f.close() def process_file(file): """Find read events in an issuu log file.""" f = open(file,"r") line = readline(f) while True: try: if re.search('"event_type":"read"', line): yield line line = readline(f) except StopIteration: break close(f) n=0 for l in proc_file(file): n += 1 print(l) print("IMP: Found " + str(n) + " matches")