简体   繁体   English

Python 将日志文件中不同行的三个字符串合并为一行

[英]Python join three strings from different lines from log file into one line

I need to concatenate three different strings from different lines into one line.我需要将来自不同行的三个不同字符串连接成一行。 My log file looks like this:我的日志文件如下所示:

2020-07-03 15:21:58,962 ERROR [AIF]: Line: 6, Error: No such member
2020-07-03 15:21:58,962 ERROR [AIF]: Actual;2020;Jun;YTD;EWHG;<Entity Currency>;A1399;401700;[None];[None];[None];[None];-7537030.790000000000
2020-07-03 15:21:58,962 ERROR [AIF]: >>>>>>401700
2020-07-03 15:21:58,962 ERROR [AIF]: 
2020-07-03 15:21:58,962 ERROR [AIF]: Line: 7, Error: The member of the Account dimension is not base level.
2020-07-03 15:21:58,962 ERROR [AIF]: Actual;2020;Jun;YTD;EWRA;<Entity Currency>;A1399;[ICP None];[None];[None];[None];[None];44984167.990000000000
2020-07-03 15:21:58,962 ERROR [AIF]: >>>>>>A1399
2020-07-03 15:21:58,962 ERROR [AIF]: 
2020-07-03 15:21:58,962 ERROR [AIF]: Line: 15, Error: The member of the Account dimension is not base level.
2020-07-03 15:21:58,962 ERROR [AIF]: Actual;2020;Jun;YTD;EWHG;<Entity Currency>;A2090;[ICP None];[None];[None];[None];[None];0.270000000000
2020-07-03 15:21:58,962 ERROR [AIF]: >>>>>>A2090

Error:错误:

Line: 6, Error: No such member | >>>>>>401700 | Actual;2020;Jun;YTD;EWHG;<Entity Currency>;A1399;401700;[None];[None];[None];[None];-7537030.790000000000

Below is my code, which is writing in different lines:下面是我的代码,它写在不同的行中:

def main():
    fo = open("C:\\Users\\yannis\\py_script\\FMC_1198.log", "r", encoding="ISO-8859-1")
    ofile = open("C:\\Users\\yannis\\py_script\\out_log.txt",'a', newline='')

    vinter = ""
    vline = ""
    vmember = ""

    f1 = fo.readlines()
    for x in f1:

        res = x.partition('Line:')[2]
        if len(res) > 0:
            vline = res
            continue
        res = x.partition('>>>>>>')[2]
        if len(res) > 0:
            vmember = res
            continue
        res = x.partition('Actual;')[2]
        if len(res) > 0:
            vinter = res
            continue

        linha = vinter + vline + vmember
        if len(linha) > 0:
            print(linha)
            ofile.write(linha)
            continue


    fo.close()
    ofile.close()

Any help much appreciated!非常感谢任何帮助!

This happens because there are \n at the end of the strings, you should write a helper function发生这种情况是因为字符串末尾有\n ,您应该编写一个帮助程序 function

def trimNewlines(st):
  return st.replace("\n")

Or或者

def trimNewlines(st):
  return st.rstrip("\n")

If you only want to remove newlines on the right of the strings and not from the middle or left如果您只想删除字符串右侧的换行符而不是中间或左侧的换行符

I was thinking of something like the following:我在想类似以下的事情:

new_log = str()

with open("old_log.txt", 'r') as input_file:
    lines = [line[37:-1] for line in input_file.readlines()]
    lines = [l for (i,l) in enumerate(lines) if i%4!=3]

    remastered = list()
    i = 0
    while i + 2 < len(lines):
        remastered.append(f"{lines[i]} | {lines[i+2]} | {lines[i+1]}")
        i += 3

    new_log = '\n'.join(remastered)

with open("new_log.txt", 'a') as input_file:
    input_file.write(new_log+'\n')

try this, using zip + list splicing试试这个,使用zip + list splicing

# pre-processing, to remove un-wanted lines & starting character's
lines = []

for l in fo.readlines():
    _, y = l.split("[AIF]:")
    if y.strip():
        lines.append(y)

with open("test.txt", 'w') as f:
    # list splicing with zip, job done..
    lines = [f"{a} | {b} | {c}\n"
             for a, b, c in zip(lines[0::3], lines[2::3], lines[1::3])]
    
    f.writelines(lines)

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

相关问题 python 正则表达式:从.txt 文件中逐行捕获不同的字符串 - python regex: capture different strings line by line from .txt file python 解析日志文件:在不同的行中找到两个特定的字符串并连接到一个并写入另一个文件! 避免空行 - python parse log file: find two specific strings in different lines and concatenate in one and write to another file! Avoiding blank lines python从内核日志中读取最后三行 - python read last three lines from kernel log 使用python将三个字符串连接到一个块中 - join three strings into one block using python 从一个文件复制到新文件时,很难将不同行上的字符串连接到同一行 - Difficulty concatenating strings on separate lines into the same line while copying from one file into a new one 从python文件中获取第一行字符串 - Getting the first strings of lines from file in python Python 将三行 .split() 合并为一行? - Python merge three lines of .split() into one line? Python,一一读取文件中的行 - Python, reading lines from a file one by one 从2个不同的行连接2个字符串(来自文本文件)-使用linecache - Concatenate 2 strings from 2 different lines (From text file) - Using linecache 如何从python中的多行字符串中删除特定的空行? - How to remove specific empty lines from multi line strings in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM