繁体   English   中英

如何在python中以自定义格式拆分输入行

[英]how to split input line in custom format in python

10.223.157.186 - - [15/Jul/2009:15:50:35 -0700]“GET /assets/js/lowpro.js HTTP/1.1”200 10469

我必须按照下面给出的输入并将其设为 %h %l %u %t \\"%r\\" %>s %b

这样我就可以有 7 个参数:

%h 是客户端的 IP 地址

%l 是客户端的身份,如果不可用则为“-”

%u 是客户端的用户名,如果不可用则为“-”

%t 是服务器完成处理请求的时间。 格式为[日/月/年:时:分:秒区]

%r 是来自客户端的请求行(双引号)。 它包含方法、路径、查询字符串和协议或请求。

%>s 是服务器发送回客户端的状态代码。

%b 是返回给客户端的对象的大小,以字节为单位。

将输入作为字符串。 假设用户的身份可以有空格,但用户名不能,

import re

full_string = input()   #python3

# First split at any one of [, ] or "
contents=re.split('[|]|"',full_string)

# Now, contents[0] = %h %l %u 
# contents[1] = %t 
# contents[2] = %r
# contents[3] = %>s %b

# For a string, directly using the split function splits the string at the passed argument, which is a space here
content_h, content_l, content_u = contents[0].split(' ')[0], contents[0].split(' ')[1:-1], contents[0].split(' ')[-1]
content_s, content_b = contents[3].split[' '][0], contents[3].split[' '][1]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM