I would like to take a text document that contains Feet+Frames values and convert them to Timecodes. For example, 0000+00 is replaced with 00:00:00:00.
I have a function to do the conversion from Feet+Frames to Timecode (16 frames per foot, framerate is 24 frames per second):
def FeetFramesToTimecode(FeetFrames):
frames = int(FeetFrames[:4])*16+int(FeetFrames[-2:])
return "%02d:%02d:%02d:%02d" % (frames/(3600*framerate), frames/(60*framerate)%60, frames/framerate%60, frames%framerate)
And then I have code that goes through the text file and sub's the Feet+Frame with timecode:
for line in input_document:
found = re.search(r'\d{4}\+\d{2}', line)
if found:
print "%s replaces %s" % (FeetFramesToTimecode(found.group()), found.group())
new_line = re.sub(r'\d{4}\+\d{2}', (FeetFramesToTimecode(found.group()), line)
output_document.write(new_line)
else:
output_document.write(line)
So, what am I doing wrong? How do I get a function to work inside of a re.sub?
resub
can take a second argument of a callable rather than just the replacement string.
If you pass a callable, it must take the match object.
You should also follow the python pep8 to make the python more readable (for other pythonistas)
Something like:
def feetframes_to_timecode(feetframes_match, framerate=24):
feetframes = feetframes_match.group()
frames = int(feetframes[:4])*16+int(feetframes[-2:])
return "%02d:%02d:%02d:%02d" % (frames/(3600*framerate),
frames/(60*framerate)%60,
frames/framerate%60,
frames%framerate)
# then just use:
for line in input_document:
output_document.write(re.sub(r'\d{4}\+\d\d', feetframes_to_timecode, line))
Your example code has an extra '(' that does not belong. This is what the line should be:
new_line = re.sub(r'\d{4}\+\d{2}', FeetFramesToTimecode(found.group()), line)
This produced output for me like you want.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.