user9654394
user9654394

Reputation:

How to create a dictionary based on regular expressions?

I am creating a set of regular expressions as requests to display data from a specific file. After that, I need to plot different requests in different figures:

    a= 'regular_expression_1'
Regular_Expression_List.append(a)
    b= 'regular_expression_2'
Regular_Expression_List.append(b)
    c= 'regular_expression_3'
Regular_Expression_List.append(c)
    d= 'regular_expression_4'
Regular_Expression_List.append(d)

I am using a list in my function

def plot_Results(Log_File):
    for reg_expression in enumerate(Regular_Expression_List):
        print (signal_sync)
        dict_node_info = loadInfoResultsFromRegularExpression(Log_File,reg_expression)
        print(dict_node_info)
        f = plt.figure(1)
        legend = []
        for mac, dico_data in dict_node_info.items():
            legend.append(mac)
            plt.plot(dico_data['timestamp'], dico_data['Counter'])

        plt.xlabel('Time (s)')
        plt.ylabel('rgular_expression')
        plt.title('Results of regular Expression')
        legend = plt.legend(legend, loc='upper left', numpoints=1, fontsize=10)
        for legend_handle in legend.legendHandles:
            legend_handle._legmarker.set_markersize(9)
        plt.grid(True)
        plt.show()
        f.savefig("C:\\Users\\User\\Desktop\\Results_resgular_Expression.png", bbox_inches='tight')

how to create a dictionary based on these regular expressions?

my_dict = {}
my_dict = {'a':'regular_expression_1', 'b':'regular_expression_2', 'c':'regular_expression_3','d':'regular_expression_4'}

In fact, I need the value in order to make my requests and loop the keys in order to rename my plots based on regular expression key (for example a,b,c,d)

Upvotes: 0

Views: 73

Answers (1)

lahsuk
lahsuk

Reputation: 1274

If all you want is a ordered dictionary of regular expressions then, you can use OrderedDict to store your re's. (As of python 3.7, you don't need to use OrderedDict as the order is preserved.) You can create a dictionary of regular expressions the following way:

import re
from collections import OrderedDict

re_dict = OrderedDict({
    'first' : r'\d+',       # find all numbers
    'second': r'\[\d+\]',   # find numbers in [x] format
    'third' : r'^The',      # all words starting with 'The'
})

f = open('test_data.txt')
text = f.read()

for re_key in re_dict.keys():
    re_value = re_dict[re_key]
    print(re.findall(re_value, text))

Or in Python 3.7, you can simply use:

re_dict = {
    'first' : r'\d+',       # find all numbers
    'second': r'\[\d+\]',   # find numbers in [x] format
    'third' : r'^The',      # all words starting with 'The'
}

Upvotes: 2

Related Questions