工作中遇到的,在一个.c文件中有很多函数,这个.c是自动生成的,需要将所有的函数通过extern放到.h中,每个函数都是UINT32 O_开头,通过正则表达式进行字符匹配以及通过linecache来截取特定行。
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
#! /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' ) |
输入:
1
2
3
4
5
6
7
8
|
UINT32 O_FUNC1(UINT32 uwA, IN UINT32 uwB, IN UINT32 * puwC, IN UINT32 * puwD, OUT UINT32 * puwE) { / / } |
输出:
1
2
3
4
5
|
extern UINT32 O_FUNC1(UINT32 uwA, IN UINT32 uwB, IN UINT32 * puwC, IN UINT32 * puwD, OUT UINT32 * puwE); |
以上这篇python实现根据指定字符截取对应的行的内容方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/xqn2017/article/details/78206988