python实现根据指定字符截取对应的行的内容方法
作者:xqn2017 时间:2021-10-23 03:24:39
工作中遇到的,在一个.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
标签:python,字符,截取
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python 元组(Tuple)操作详解
2023-06-28 15:36:39
![](https://img.aspxhome.com/file/2023/3/59133_0s.png)
马化腾关于产品设计与用户体验的培训
2009-02-12 11:45:00
python用turtle库绘画圣诞树
2023-05-24 19:35:40
![](https://img.aspxhome.com/file/2023/9/86369_0s.jpg)
asp使用XMLHTTP下载远程数据输出到浏览器
2007-11-04 10:34:00
css把超出的部分显示为省略号的方法兼容火狐
2010-10-07 09:02:44
图解Golang的GC垃圾回收算法
2023-07-12 23:25:45
![](https://img.aspxhome.com/file/2023/9/93659_0s.png)
python交互式图形编程实例(一)
2022-11-12 14:44:53
Python中常用的os操作汇总
2022-12-13 08:30:16
![](https://img.aspxhome.com/file/2023/2/75302_0s.png)
Flask request 对象介绍
2022-11-01 23:45:35
![](https://img.aspxhome.com/file/2023/3/78543_0s.png)
Bootstrap每天必学之响应式导航、轮播图
2023-08-15 03:29:45
php文件怎么打开 如何执行php文件
2023-11-15 05:51:46
![](https://img.aspxhome.com/file/2023/1/96241_0s.gif)
python SOCKET编程基础入门
2021-04-20 17:22:33
![](https://img.aspxhome.com/file/2023/6/87466_0s.jpg)
Django中处理出错页面的方法
2023-08-28 14:41:41
python 使用csv模块读写csv格式文件的示例
2021-04-24 15:58:28
深入理解Python虚拟机中元组(tuple)的实现原理及源码
2022-07-12 14:14:21
![](https://img.aspxhome.com/file/2023/0/79660_0s.png)
python3.6根据m3u8下载mp4视频
2021-05-22 00:20:03
![](https://img.aspxhome.com/file/2023/5/79795_0s.png)
Laravel框架数据库CURD操作、连贯操作总结
2023-11-17 07:22:26
垂直对齐:vertical-align属性
2008-07-11 20:55:00
![](https://img.aspxhome.com/file/UploadPic/20087/11/2008711211236236s.gif)
Python学习之shell脚本的使用详解
2023-10-01 17:57:51
4款Javascript放大镜特效脚本
2009-10-14 20:46:00
![](https://img.aspxhome.com/file/UploadPic/200910/14/javascript-9-7-6j-25s.jpg)