python implements the method of intercepting the content of the corresponding row based on the specified character
- 2020-12-22 17:44:31
- OfStack
I came across in my work, there are a lot of functions in one.c file, this.c is automatically generated, you need to put all the functions in.h through extern, each function starts with UINT32 O_, uses regular expressions for character matching and uses linecache to intercept specific lines.
The code is as follows:
#! /usr/bin/env python
# encoding:utf-8
# ! /usr/bin/env python
# encoding:utf-8
import re
import linecache
file = 'D:\PUSCH_job3.txt'
outfile = 'D:\outfile3.txt'
lineNumber = 1
with open(file,'r') as f:
number = []
for line in f.readlines():
m = re.findall(r"UINT32 O_\w+",line) # Match containing character 'UINT32 O_' The rows of
if m:
number.append(lineNumber)
n = re.findall(r"OUT \w+",line) # Assuming that only the 1 a OUT
if n:
number.append(lineNumber)
lineNumber += 1
with open(outfile, 'w+') as f_w:
for j in range(len(number)):
if j%2 == 0:
start = number[j]
end = number[j+1]
destlines = linecache.getlines(file)[start-1:end] # The interception start-end Line characters, not included start-1, But with end line
f_w.write('extern ')
for i in range(len(destlines)):
if i != len(destlines)-1:
f_w.write(destlines[i])
else:
f_w.write(destlines[i].replace('\n',';\n'))
f_w.write('\n')
Input:
UINT32 O_FUNC1(UINT32 uwA,
IN UINT32 uwB,
IN UINT32* puwC,
IN UINT32* puwD,
OUT UINT32* puwE)
{
//
}
Output:
extern UINT32 O_FUNC1(UINT32 uwA,
IN UINT32 uwB,
IN UINT32* puwC,
IN UINT32* puwD,
OUT UINT32* puwE);