import re


def norm_freqs(data, expression, count_name=str, normalize=True, analyze=True):
    """Get frequencies (normalized = optional) of a regex pattern in a Series with one or more strings. 

    Args:
        data (DataFrame): a dataframe with texts to extract frequencies from.
        expression (re.compile): a regex pattern to count occurrences of in each text.
        count_name (str, optional): a name for the counted feature. Defaults to str.
        normalize (bool, optional): [description]. Defaults to True.

    Returns:
        list: list of dicts with key = frequency name, value = frequency.
    """
    # List to store frequencies
    # freqList = list()

    # Loop through each entry in the list of strings.
    # for e in stringList:
    #     # Join to a regular string
    #     text = ' '.join(e)

    #     # Construct a dict for each entry with freuncies.
    #     c = {count_name : len([char for char in text if char in expression])}

    # Get frequencies of a regex in a pandas column, normalize if set to True.
    c = data.apply(lambda x: len(re.findall(
        expression, x))/len(x) if normalize == True else len(re.findall(expression, x)))

    ### Adapted from https://stackoverflow.com/a/45452966 ###

    # Cast frequencies Series to list of dicts.
    cList = [{count_name: x[1]} for x in c.items()]

    ### Accessed 10-05-2021 ###
    if analyze == True:
        return cList
    else:
        return c