python - 在Python中为split()创建动态 "variable layout"

标签 python dynamic split

我有一个解析 IIS 日志的脚本,目前它使用 split 将 IIS 字段值放入多个变量中逐一获取日志行,如下所示:

date, time, sitename, ip, uri_stem, whatever = log_line.split(" ")

而且,它在默认设置下工作得很好。但是,如果其他人使用不同的日志字段布局(不同的顺序或不同的日志字段,或两者兼而有之),他将必须在源代码中找到此行并进行修改。这个人还必须知道如何修改它,以便不会出现任何中断,因为显然这个变量稍后会在代码中使用。

我怎样才能使这个更通用,以某种方式包含某种列表,其中包含用户可以修改的IIS日志字段布局(配置变量,或脚本开头的字典/列表)稍后将用于保存日志行值?这就是我所认为的——“动态”。我正在考虑也许使用 for 循环和字典来做到这一点,但我想与使用 split() 相比,它会对性能产生很大的影响,或者不是吗?有人对如何/应该如何做到这一点有建议吗?

这是否值得这么麻烦,或者我应该为使用该脚本的任何人记下在哪里更改包含 log_line.split() 的代码行、如何操作以及要注意什么?

谢谢。

最佳答案

如果只有字段的顺序可能不同,则可以处理每行的验证并自动调整信息的提取以适应检测到的顺序。
我认为在正则表达式的帮助下很容易做到这一点。

如果不仅顺序不同,字段的数量和性质也可能不同,我认为仍然可以做同样的事情,但前提是提前知道可能的字段。

共同的条件是字段必须具有足够强大的“个性”以便易于区分

在我看来,如果没有更准确的信息,没有人可以走得更远

8 月 15 日星期一 9:39 GMT+0:00

spilp.py 中似乎存在错误:
一定是

使用 codecs.open(file_path, 'r',encoding='utf-8',errors='ignore') 作为 log_lines:
不是
with open(file_path, 'r',encoding='utf-8',errors='ignore') 作为 log_lines:
后者使用内置的 open() ,它没有相关的关键字

8 月 15 日星期一 16:10 GMT+0:00

目前,在示例文件中,字段按以下顺序排列:

date
time
s-sitename
s-ip
cs-method
cs-uri-stem
cs-uri-query
s-port cs-username
c-ip
cs(User-Agent)
sc-status
sc-substatus
sc-win32-status

.

假设您想按以下顺序提取每行的值:

s-port
time
date
s-sitename
s-ip
cs(User-Agent)
sc-status
sc-substatus
sc-win32-status
c-ip
cs-username
cs-method
cs-uri-stem cs-uri-query

以相同的顺序将它们分配给以下标识符:

s_port
time
date
s_sitename
s_ip
cs_user_agent
sc_status
sc_substatus
sc_win32_status
c_ip
cs_username
cs_method
cs_uri_stem
cs_uri_query

正在做

s_port,
time, date,
s_sitename, s_ip,
cs_user_agent, sc_status, sc_substatus, sc_win32_status,
c_ip,
cs_username,
cs_method, cs_uri_stem, cs_uri_query = line_spliter(line)

使用函数line_spliter()

我知道,我知道,您想要的是相反的:按照文件当前的顺序恢复在文件中读取的值,以防万一存在一个文件的顺序与一般当前文件的顺序不同。

但我仅以此为例,目的是让示例文件保持原样。否则,我需要创建一个具有不同顺序值的其他文件来公开示例。

无论如何,算法不依赖于示例。它取决于定义执行正确分配所必须获得的值的连续性所需的顺序。

在我的代码中,这个所需的顺序是使用对象ref_fields设置的

我认为我的代码及其执行本身就可以帮助理解原理。

import re


ref_fields = ['s-port',
              'time','date', 
              's-sitename', 's-ip',
              'cs(User-Agent)', 'sc-status', 
              'sc-substatus', 'sc-win32-status',
              'c-ip',
              'cs-username',
              'cs-method', 'cs-uri-stem', 'cs-uri-query']

print 'REF_FIELDS :\n------------\n%s\n' % '\n'.join(ref_fields)


############################################
file_path = 'I:\\sample[1].log'                  # Path to put here
############################################


with open(file_path, 'r') as log_lines:
    line = ''
    while line[0:8]!='#Fields:':
        line = next(log_lines)
    # At this point, line is the line containing the fields keywords
    print 'line of the fields keywords:\n----------------------------\n%r\n' % line

    found_fields = line.split()[1:]
    len_found_fields = len(found_fields)
    regex_extractor = re.compile('[ \t]+'.join(len_found_fields*['([^ \t]+)']))
    print 'list found_fields of keywords in the file:\n------------------------------------------\n%s\n' % found_fields

    print '\nfound_fields == ref_fields  is ',found_fields == ref_fields




    if found_fields == ref_fields:
        print '\nNORMAL ORDER\n------------'
        def line_spliter(line):
            return line.split()

    else:
        the_order = [ found_fields.index(fild) + 1 for fild in ref_fields]
        # the_order is the list of indexes localizing the elements of ref_fields 
        # in the order in which they succeed in the actual line of found fields keywords
        print '\nSPECIAL ORDER\n-------------\nthe_order == %s\n\n\n======================' % the_order
        def line_spliter(line):
            return regex_extractor.match(line).group(*the_order)



    for i in xrange(1):
        line = next(log_lines)
        (s_port,
        time, date,
        s_sitename, s_ip,
        cs_user_agent, sc_status, sc_substatus, sc_win32_status,
        c_ip,
        cs_username,
        cs_method, cs_uri_stem, cs_uri_query) = line_spliter(line)
        print ('LINE :\n------\n'
               '%s\n'
               'SPLIT LINE :\n--------------\n'
               '%s\n\n'
               'REORDERED SPLIT LINE :\n-------------------------\n'
               '%s\n\n'
               'EXAMPLE OF SOME CORRECT BINDINGS OBTAINED :\n-------------------------------------------\n'
               'date == %s\n'
               'time == %s\n'
               's_port == %s\n'
               'c_ip == %s\n\n'
               '======================') % (line,'\n'.join(line.split()),line_spliter(line),date,time,s_port,c_ip)




# ---- split each logline into multiple variables, populate dictionaries and db ---- #      
def splitLogline(log_line):
        # needs to be dynamic (for different logging setups)
        s_port,
        time, date,
        s_sitename, s_ip,
        cs_user_agent, sc_status, sc_substatus, sc_win32_status,
        c_ip,
        cs_username,
        cs_method, cs_uri_stem, cs_uri_query = line_spliter(line)

结果

REF_FIELDS :
------------
s-port
time
date
s-sitename
s-ip
cs(User-Agent)
sc-status
sc-substatus
sc-win32-status
c-ip
cs-username
cs-method
cs-uri-stem
cs-uri-query

line of the fields keywords:
----------------------------
'#Fields: date time s-sitename s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) sc-status sc-substatus sc-win32-status \n'

list found_fields of keywords in the file:
------------------------------------------
['date', 'time', 's-sitename', 's-ip', 'cs-method', 'cs-uri-stem', 'cs-uri-query', 's-port', 'cs-username', 'c-ip', 'cs(User-Agent)', 'sc-status', 'sc-substatus', 'sc-win32-status']


found_fields == ref_fields  is  False

SPECIAL ORDER
-------------
the_order == [8, 2, 1, 3, 4, 11, 12, 13, 14, 10, 9, 5, 6, 7]


======================
LINE :
------
2010-01-01 00:00:03 SITENAME 192.168.1.1 GET /news-views.aspx - 80 - 66.249.72.135 Mozilla/5.0+(compatible;+Googlebot/2.1;++http://www.google.com/bot.html) 200 0 0

SPLIT LINE :
--------------
2010-01-01
00:00:03
SITENAME
192.168.1.1
GET
/news-views.aspx
-
80
-
66.249.72.135
Mozilla/5.0+(compatible;+Googlebot/2.1;++http://www.google.com/bot.html)
200
0
0

REORDERED SPLIT LINE :
-------------------------
('80', '00:00:03', '2010-01-01', 'SITENAME', '192.168.1.1', 'Mozilla/5.0+(compatible;+Googlebot/2.1;++http://www.google.com/bot.html)', '200', '0', '0\n', '66.249.72.135', '-', 'GET', '/news-views.aspx', '-')

EXAMPLE OF SOME CORRECT BINDINGS OBTAINED :
-------------------------------------------
date == 2010-01-01
time == 00:00:03
s_port == 80
c_ip == 66.249.72.135

======================

此代码仅适用于文件中的字段被打乱的情况,但其数量与正常的已知字段列表相同。

也可能发生其他情况,例如文件中的值少于已知和等待的字段。如果您需要针对这些其他情况的更多帮助,请解释可能会发生哪些情况,我将尝试调整代码。

.

我想我会对我在 spilp.py 中快速阅读的代码做很多评论。当我有时间的时候我会写它们。

关于python - 在Python中为split()创建动态 "variable layout",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7036984/

相关文章:

java - 使用正则表达式拆分一个简单的 JSON 结构

python - Pandas 被最后一个分隔符分割

c - 文件到c中的动态数组

jquery - 对 jquery 监听器的工作方式感到困惑

python - Buildbot:动态创建新的 Builder 或 BuilderConfig 或项目

python - 将 numpy.fromiter 与自定义函数一起使用

sharepoint - 在 SharePoint 中创建动态站点地图

java - 你可以将 string.split 数组转换为 JButtons

python - 从python中的列表中删除项目

python - 如何在 'scons' 中为命令生成器指定 COMSTR