如何在文本文件中展开包装的行,重新格式化文本文件

时间:2011-09-14 05:00:40

标签: python python-2.7 text file-io

我需要帮助找到一个Python解决方案来重新格式化包装的行/重写日志文件,因此没有描述的换行符。这将使我能够继续在不间断的线路上找到。

* .log中的每个条目都带有时间戳。太长的行按预期包装,但是:包裹的部分也带有时间戳。 “>” 中(大于)是线已经包裹的唯一指示 - 发生在位置37上。>该日志来自* nix机器。

我不知道如何开始...

2011-223-18:31:11.737  VWR:tao       abc exec /home/abcd/abcd9.94/bin/set_specb.tcl -s DL 2242.500000 5
2011-223-18:31:11.737                > -20.000000 10
###needs to be rewritten as:
2011-223-18:31:11.737  VWR:tao       abc exec /home/abcd/abcd9.94/bin/set_specb.tcl -s DL 2242.500000 5 -20.000000 10

另一个

2011-223-17:40:07.039  EVT:703       agc_drift_cal.tcl: out of tolerance drift of 5.3080163871 detected! Downlink Alignmen
2011-223-17:40:07.039                >t check required.
###these lines deleted and consolodated as one:
2011-223-17:40:07.039  EVT:703       agc_drift_cal.tcl: out of tolerance drift of 5.3080163871 detected! Downlink Alignment check required.

我不知道如何开始,除了......

for filename in validfilelist:
    logfile = open(filename, 'r')
    logfile_list = logfile.readlines()
    logfile.close
    for line in logfile_list:

3 个答案:

答案 0 :(得分:0)

for filename in validfilelist:
    logfile = open(filename, 'r')
    logfile_list = logfile.readlines()
    logfile.close()
    for line in logfile_list:
        if(line[21:].strip()[0] == '>'):
           #line_is_broken
        else:
           #line_is_not_broken

答案 1 :(得分:0)

#!/usr/bin/python

import re

#2011-223-18:31:11.737                > -20.000000 10
ptn_wrp = re.compile(r"^\d+-\d+-\d+:\d+:\d+.\d+\s+>(.*)$")

validfilelist = ["log1.txt", "log2.txt"]

for filename in validfilelist:
    logfile = open(filename, 'r')
    logfile_new = open("%s.new" % filename, 'w')
    for line in logfile:
        line = line.rstrip('\n')
        m = ptn_wrp.match(line)
        if m:
            logfile_new.write(m.group(1))
        else:
            logfile_new.write("\n")
            logfile_new.write(line)
    logfile_new.write("\n")
    logfile.close()
    logfile_new.close()

当该行不是换行时写入新行。唯一的副作用是开头的空行。不应该是日志分析的问题。新文件是处理结果。

答案 2 :(得分:0)

如果你把它包装在filecontext中,这就可以了。

f = [
    "2011-223-18:31:11.737  VWR:tao       abc exec /home/abcd/abcd9.94/bin/set_specb.tcl -s DL 2242.500000 5",
    "2011-223-18:31:11.737                > -20.000000 10",
    "2011-223-17:40:07.039  EVT:703       agc_drift_cal.tcl: out of tolerance drift of 5.3080163871 detected! Downlink Alignmen",
    "2011-223-17:40:07.039                >t check required.",
    ]

import re

wrapped_line = "\d{4}-\d{3}-\d{2}:\d{2}:\d{2}\.\d{3} *>(.*$)"

result = [""]
for line in f:
    thematch = re.match(wrapped_line,line)
    if thematch:
        result[-1] += thematch.group(1)
    else:
        result.append(line)

print result