Example of a persistent list class (Python)

vegaseat 1 Tallied Votes 671 Views Share

Just an example of a persistent list class that could have interesting applications in data mining.

'''Class__persist1.py
find all integers in a series of texts
create a persistent list of all finds

the emphasis is on the creation of a persistent list
and the implementation of __call__()

tested with Python27 and Python34
'''

import re

class Persist_list_int():
    """
    class to make a list persistent
    """
    def __init__(self):
        # this list is persistent
        self.all_items = []

    def __call__(self, text):
        """
        allows class instance to be called with argument text
        """
        # a simple test of the persistent list
        # use regex to find all integers in a given text
        items = re.findall("[-+]*\d+", text)
        self.all_items.extend(items)
        return self.all_items


# create class instance
find_int = Persist_list_int()

# call instance
# found integers are added to the persistent list
print(find_int('12 days and 17 hours'))   # ['12', '17']
print(find_int('Thermometer shows -15'))  # ['12', '17', '-15']
print(find_int('we are leaving at 6:45')) # ['12', '17', '-15', '6', '45']
print(find_int('you owe me $123.48'))     # ['12', '17', '-15', '6', '45', '123', '48']