Skip to content Skip to sidebar Skip to footer

Replace String Without Python Re Module?

Say my file looks like this: foo bar BeginObject something something ObjectAlias NotMe lines more lines BeginKeyframe 22 12 foo bar default foo default bar default EndKeyframe E

Solution 1:

full code goes:

interested_objects = ['HeyThere', 'anotherone',]

buff = []
obj_flag = False
keyframe_flag = Falsewithopen('in') as f, open ('out', 'w') as of:
    for line in f:
        line = line.strip()

        if line.startswith('ObjectAlias'):
            assertnot obj_flag
            assertnot keyframe_flag
            if line.split()[1] in interested_objects:
                obj_flag = Trueifnot obj_flag:
            print >>of, line
            continueif'EndObject'in line:
            assertnot keyframe_flag
            obj_flag = Falseif'BeginKeyframe'in line:
            assertnot keyframe_flag
            keyframe_flag = Trueif keyframe_flag:
            buff.append(line)
        else:
            print >>of, line

        if'EndKeyframe'in line:
            parts = buff[0].split()
            new_line = '{} {} {}'.format(parts[0], len(buff)-2, parts[2])
            print >>of, new_line
            print >>of, '\n'.join(buff[1:])
            buff = []
            keyframe_flag = False

Solution 2:

just open the input.txt with 'r' mode for read only, and open another file output.txt with 'w' mode to write to new file. And don't need the seek and tell as well, just process it line by line while reading input file.

A buffer is use to keep the the lines once BeginKeyFrame found. Release the buffer to ouput file when EndObject found.

Quick edit the code as below, should works but might not so elegant and pythonic

objectlist = ['GoodMoring', 'GoodAfternoon']
withopen('input.txt', 'r') as f, open('output.txt', 'w') as fo:
    found = False
    begin_frame = False
    buffer = []
    for line in f:
        if line.startswith('ObjectAlias'):
            found = any('ObjectAlias ' + objectname in line for objectname in objectlist)
        elif line.startswith('EndObject'):
            if found and begin_frame:
                # modify and write all buffer into output file
                buffer[0] = buffer[0].replace(buffer[0].split()[1], str(frames), 1)
                for i in buffer:
                    fo.write(i)
            buffer = [] # clear buffer
            found = False
            begin_frame = Falseelif line.startswith('BeginKeyframe'):
            begin_frame = True
            frames = 0if found and begin_frame:
            buffer.append(line)
            if'default'in line:
                frames += 1else:
            fo.write(line)

Solution 3:

The file temp.txt contains your input. There's no actual need to use "re" module for these simple operations.

asource = open('temp.txt').read().split('\n')
aframe = -1defwrapFrame():
    global aframe
    if aframe < 0: return
    asource[aframe][1] = str(asource[aframe][1])
    asource[aframe] = ' '.join(asource[aframe])
    aframe = -1for i in xrange(len(asource)):
    aline = asource[i]

    if aframe > -1:
        if'default'in aline:
            asource[aframe][1] += 1elif'EndKeyframe'in aline:
            wrapFrame()
    elif'BeginKeyframe'in aline:
        aframe = i
        asource[i] = aline.split(' ')
        asource[i][1] = 0

wrapFrame()

asource = '\n'.join(asource)
print asource

Post a Comment for "Replace String Without Python Re Module?"