首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何创建基于正则表达式的字典?

如何创建基于正则表达式的字典?
EN

Stack Overflow用户
提问于 2019-01-13 17:01:10
回答 1查看 59关注 0票数 0

我正在创建一组正则表达式作为请求,以显示特定文件中的数据。在此之后,我需要用不同的图形绘制不同的请求:

代码语言:javascript
运行
复制
    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)

我在我的函数中使用列表

代码语言:javascript
运行
复制
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')

如何根据这些正则表达式创建字典?

代码语言:javascript
运行
复制
my_dict = {}
my_dict = {'a':'regular_expression_1', 'b':'regular_expression_2', 'c':'regular_expression_3','d':'regular_expression_4'}

实际上,我需要该值,以便发出请求并循环关键字,以便根据正则表达式关键字(例如a、b、c、d)重命名我的图。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-13 17:20:16

如果您想要的只是一个正则表达式的有序字典,那么可以使用OrderedDict来存储re。(从Python3.7开始,您不需要使用OrderedDict,因为顺序被保留了。)您可以通过以下方式创建正则表达式的字典:

代码语言:javascript
运行
复制
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))

或者在Python 3.7中,您可以简单地使用:

代码语言:javascript
运行
复制
re_dict = {
    'first' : r'\d+',       # find all numbers
    'second': r'\[\d+\]',   # find numbers in [x] format
    'third' : r'^The',      # all words starting with 'The'
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54167389

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档