如何展开文本文件中的换行,重新格式化文本fi

2024-05-04 15:23:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要帮助找到一个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

还有一个

^{pr2}$

我不知道怎么开始,除了。。。在

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

Tags: gthomeforbin时间tclexecdl
3条回答
#!/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()

当该行不是换行符时,请写入新行。唯一的副作用是开头的空行。对于日志分析来说应该不是问题。新文件是处理后的结果。在

如果将其包装在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
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

相关问题 更多 >