How to post a new line at the end of each Title region with Title[Name]2 if there are at least 5 consecutive lines within each region?

后端 未结 1 1709
小鲜肉
小鲜肉 2021-01-29 11:22

I guess the easiest way to achieve posting a new line with *Title[Name]2 at the end of each *Title region where there at least 5 consecutive lines containing 1 1 1 1 would be vi

相关标签:
1条回答
  • 2021-01-29 11:54

    You added code in the part which happens when we see a new *Title line, but of course the counter should be incremented when you are in a region where the current line ends with 1 1 1 1. Here is a refactoring which moves things around a bit for your new requirement.

    transitions = dict()
    reg_count = 0
    reg_end = -1
    current_title = None
    
    with open("test.txt","r") as testfile:
        content = testfile.readlines()
        
    for idx, line in enumerate(content):
        if line.startswith('*Title '):
            current_title = line.rstrip('\n') + '2\n'
        elif line.strip().endswith(' 1 1 1 1'):
            reg_count += 1
            reg_end = idx
        elif reg_count:
            if current_title and reg_count >= 5:
                transitions[reg_end] = current_title
            reg_count = 0
    if current_title and reg_count >= 5:
        transitions[reg_end] = current_title
    
    with open("test.txt", "w") as output:
        for idx, line in enumerate(content):
            output.write(line)
            if idx in transitions:
                output.write(transitions[idx])
    

    Demo: https://ideone.com/pJaVvq

    If you want to develop this further, add print statements which show the value of pertinent variables in each section so you can see what's going on when the program processes a simple file. I don't believe you can make meaningful changes to code before you understand how it works.

    0 讨论(0)
提交回复
热议问题