【问题标题】:how to split input line in custom format in python如何在python中以自定义格式拆分输入行
【发布时间】:2016-10-09 10:55:06
【问题描述】:

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 是返回给客户端的对象的大小,以字节为单位。

【问题讨论】:

  • 我猜你忘记粘贴代码了。您只提到了您的要求。

标签: python python-3.x input


【解决方案1】:

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

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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-29
    相关资源
    最近更新 更多