python - 如何根据正则表达式创建字典?
问题描述
我正在创建一组正则表达式作为显示来自特定文件的数据的请求。之后,我需要在不同的数字中绘制不同的请求:
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)
我在我的函数中使用列表
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')
如何根据这些正则表达式创建字典?
my_dict = {}
my_dict = {'a':'regular_expression_1', 'b':'regular_expression_2', 'c':'regular_expression_3','d':'regular_expression_4'}
事实上,我需要这个值来发出我的请求并循环键以便根据正则表达式键重命名我的图(例如 a、b、c、d)
解决方案
如果你想要的只是一个有序的正则表达式字典,那么你可以使用 OrderedDict 来存储你的 re's。(从 python 3.7 开始,您不需要使用 OrderedDict,因为保留了顺序。)您可以通过以下方式创建正则表达式字典:
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 中,您可以简单地使用:
re_dict = {
'first' : r'\d+', # find all numbers
'second': r'\[\d+\]', # find numbers in [x] format
'third' : r'^The', # all words starting with 'The'
}
推荐阅读
- sql-server - SSIS 与 SVN 的集成
- c# - 将 QnAMaker 示例与 QnAMakerDialog 一起使用时出错
- python-3.x - 在scrapy的启动请求中调用http://url
- trace32 - 查询函数符号是否存在
- c# - XML 元素和属性的多个名称
- php - Laravel 将参数从路由传递到控制器分解页面
- android - 当 Android Oreo 版本中的堆栈中的应用程序进入暂停或停止时,LcoationChanged 未调用
- elasticsearch - 这些 Elasticsearch 索引的用途是什么?
- python - 如何使用 python 从网站的搜索栏中提取数据?
- css - 用于重复的样式元素,由事件触发