I’ve had a really clunky program to track what I do. It lets me know how much volume I’m reading calculated each 30 min based a logfile.
I’ve decided to get a little more sophisticated with the program because it has grown to the point where it’s painful for me to edit, and if I wrote it, it must be completely abstruse to someone else.
I have never used a class in python but it solves many issues for me:
- Cleans up the code
- Moves functions to a module for importing and repurposing
- Teaches me how to construct a class properly
- Allows parsing of text with a structure that makes sense
- Class instance attributes now make inherent sense
- Eliminates having to bring global var into functions for modification
- The class instance can access global counters
- The class output can eliminate the need for global counters
- Allows me to expand to the class to perform other manipulation
- calculating age of patient
- SQL archival
- Works in python 2 and 3
- Uses the Regex from hell
import re class Parser: """ A class to parse data strings into components USE: from parser_fx import * result = Parser() ## Instantiate class result.parse(study) ## Pass the instance a study string result.XXXXXXX ## Attributes of result now available """ def __init__(self): """ Simply establishes the regex expression""" self.regex = re.compile(r'([\'A-Z\s-]+)(\[.+||\s])\s*' '(CURRENT STUDY:)([A-Z\s/\[\]]+)' '([\d-]+)\s([\d:]+)\s' '(\[DOB:[\s0-9/]+])\s+(\[ID:.+])') def parse(self, study_string=('SIMPSON HOMER J[Prelim report]CURRENT STUDY:' 'CT HEAD 2016-01-01 23:59:59 [DOB: 1111/1/11 ] [ID: 1234567]')): """Parser with failure options""" self.study_string = study_string try: self.matchobj = self.regex.match(self.study_string) ## Attributes: name, prelim/final, study, date, time dob, ID self.name = self.matchobj.group(1) self.type = self.matchobj.group(2)[1:7].rstrip() self.study_name = self.matchobj.group(4) self.date = self.matchobj.group(5) self.time = self.matchobj.group(6) self.DOB = self.matchobj.group(7) self.ID = self.matchobj.group(8)[1:-1] except: print("REGEX Match Failed") """ Leaving here as an example to follow def ID(self): ''' returns study ''' self.ID = self.matchobj.group(8) return self.ID """ """ study= ('SIMPSON HOMER J[Prelim report]CURRENT STUDY:' 'CT HEAD 2016-01-01 23:59:59 [DOB: 1111/1/11 ] [ID: 1234567]') result = Parser() result.parse(study) print("%s | %s | %s | %s | %s | %s" %(result.type, result.name, result.study_name, result.date, result.time, result.ID)) """
After testing for a week, I’ll report back on success or failure.