使用正则表达式从4个列表中创建多个词典 [英] Create multiple dictionaries from 4 lists using regex
本文介绍了使用正则表达式从4个列表中创建多个词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下txt文件:
197.109.77.178 - kertzmann3129 [21/Jun/2019:15:45:25 -0700] "DELETE /virtual/solutions/target/web+services HTTP/2.0" 203 26554
156.127.178.177 - okuneva5222 [21/Jun/2019:15:45:27 -0700] "DELETE /interactive/transparent/niches/revolutionize HTTP/1.1" 416 14701
100.32.205.59 - ortiz8891 [21/Jun/2019:15:45:28 -0700] "PATCH /architectures HTTP/1.0" 204 6048
168.95.156.240 - stark2413 [21/Jun/2019:15:45:31 -0700] "GET /engage HTTP/2.0" 201 9645
71.172.239.195 - dooley1853 [21/Jun/2019:15:45:32 -0700] "PUT /cutting-edge HTTP/2.0" 406 24498
180.95.121.94 - mohr6893 [21/Jun/2019:15:45:34 -0700] "PATCH /extensible/reinvent HTTP/1.1" 201 27330
我想创建一个函数,将它们转换成多个字典,其中每一行都是一个字典:
I want to create a function that converts these to multiple dictionaries where each line is a dictionary :
example_dict = {主机":"146.204.224.152",用户名":"feest6811",时间":"21/Jun/2019:15:45:24-0700&","request":"POST/incentivize HTTP/1.1"}
到目前为止,我能够做到这一点,为所有项目创建4个列表,但我不知道如何为每行创建多个dic:
I was able to do this so far, create 4 lists for all the items but I didn't know how to create multiple dics for each line:
import re
def logs():
with open("assets/logdata.txt", "r") as file:
logdata = file.read()
host = (re.findall('(.*?)\-',logdata))
username = re.findall('\-(.*?)\[',logdata)
time = re.findall('\[(.*?)\]', logdata)
request = re.findall('\"(.*?)\"',logdata)
#for line in range(len(logdata)):
#dc = {'host':host[line], 'user_name':user_name[line], 'time':time[line], 'request':request[line]}
推荐答案
我现在正在做这门课程,得到的答案是
I am doing this course rightnow and the answer i got is
import re
def logs():
with open("assets/logdata.txt", "r") as file:
logdata = file.read()
# YOUR CODE HERE
pattern='''
(?P<host>[\w.]*)
(\ -\ )
(?P<user_name>([a-z\-]*[\d]*))
(\ \[)
(?P<time>\w.*?)
(\]\ \")
(?P<request>\w.*)
(\")
'''
lst=[]
for item in re.finditer(pattern,logdata,re.VERBOSE):
lst.append(item.groupdict())
print(lst)
return lst
这篇关于使用正则表达式从4个列表中创建多个词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文