网络编程
位置:首页>> 网络编程>> Python编程>> python实现根据指定字符截取对应的行的内容方法

python实现根据指定字符截取对应的行的内容方法

作者:xqn2017  发布时间:2021-10-23 03:24:39 

标签:python,字符,截取

工作中遇到的,在一个.c文件中有很多函数,这个.c是自动生成的,需要将所有的函数通过extern放到.h中,每个函数都是UINT32 O_开头,通过正则表达式进行字符匹配以及通过linecache来截取特定行。

代码如下:


#! /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) #匹配含有字符'UINT32 O_'的行
if m:
number.append(lineNumber)
n = re.findall(r"OUT \w+",line) #假设只有一个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] #截取start-end行的字符,不包括start-1,但包含end行
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')

输入:


UINT32 O_FUNC1(UINT32 uwA,
IN UINT32 uwB,
IN UINT32* puwC,
IN UINT32* puwD,
OUT UINT32* puwE)
{
//
}

输出:


extern UINT32 O_FUNC1(UINT32 uwA,
IN UINT32 uwB,
IN UINT32* puwC,
IN UINT32* puwD,
OUT UINT32* puwE);

来源:https://blog.csdn.net/xqn2017/article/details/78206988

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com