python实现修改固定模式的字符串内容操作示例
作者:团长sama 时间:2023-05-13 21:44:04
本文实例讲述了python实现修改固定模式的字符串内容操作。分享给大家供大家参考,具体如下:
说明
字符串模式是开头可能有空格,之后可能存在多个小数点,然后后面跟着一个数字,数字可能是小数,数字后可能存在空格。
任务要求删去开头的小数点,如下:
" …78 " 修改为" 78 "
" …7.889 " 修改为" 7.889 "
“.9.8"修改为"9.8”
代码示例
注意这里正则的模式和分组的用法
import os
import re
testStr=r"...7.88 "
pattern=re.compile(r'(?P<lblank> *)(?P<point>\.*)(?P<realcontent>\d+\.?\S*)(?P<rblank> *)')
finalStr=pattern.search(testStr)
print(finalStr)
result=finalStr.group("lblank")+finalStr.group("realcontent")+finalStr.group("rblank")
print("result is: {}".format(result))
输出:
<_sre.SRE_Match object; span=(0, 8), match='...7.88 '>
result is: 7.88
拓展
说明
用来处理样本用的。标签是一个txt文件包含了图片的内容,内容的模式是(空格*)+(.*)+(小数或者整数)+(空格凑齐位数)。
脚本实现功能是:将第二部分里面的小数点去除(用正则分组去),修正原本的标签文件,并将标签两边占位用的空格去掉,形成新的标签,将新标签文件和对应的图片移动到以标签长度命名的文件夹中。由于文件量有40w+,使用多进程处理。
拓展代码
import os
import re
from multiprocessing import Pool
import shutil
def getAllFilePath(pathFolder,filter=[".jpg",".txt"]):
#遍历文件夹下所有图片
allCropPicPathList=[]
allTXTPathList=[]
#maindir是当前搜索的目录 subdir是当前目录下的文件夹名 file是目录下文件名
for maindir,subdir,file_name_list in os.walk(pathFolder):
for filename in file_name_list:
apath=os.path.join(maindir,filename)
ext=os.path.splitext(apath)[1]#返回扩展名
if ext==filter[0] and ('_crop' in filename):
allCropPicPathList.append(apath)
elif ext==filter[1] and ('_crop' in filename):
allTXTPathList.append(apath)
return list(zip(allCropPicPathList,allTXTPathList))
#分析样本 对模式错误(即删去在开头空格和数字之间的.)的进行修正
def checkTxtContent(txtcontent,txtPath):
pattern=re.compile(r'(?P<lblank> *)(?P<point>\.*)(?P<realcontent>\d+\.?\S*)(?P<rblank> *)')
finalStr=pattern.search(txtcontent)
if len(finalStr.group("point"))!=0:
resultStr=finalStr.group("lblank")+finalStr.group("realcontent")+finalStr.group("rblank")
with open(txtPath,'w') as fw:
fw.write(resultStr)
with open(r'E:\Numberdata\wrong.txt','a') as fw:
fw.write(txtPath+"\n")
print(txtPath,"is wrong!")
return resultStr
else:
return txtcontent
#移动图片到对应长度的文件夹 标签label进行修改
def dealSampleList(samplePathList,saveBaseDir):
for samplePath in samplePathList:
txtPath=samplePath[1]
picPath=samplePath[0]
newtxtStr=""
with open(txtPath,'r') as fr:
txtStr=fr.readline()
newtxtStr=checkTxtContent(txtStr,txtPath)
newtxtStr=newtxtStr.strip()
# 创建对应的文件夹
saveDir=os.path.join(saveBaseDir,str(len(newtxtStr)))
if not os.path.exists(saveDir):
os.mkdir(saveDir)
newTxtName=os.path.basename(txtPath)
newPicName=os.path.basename(picPath)
with open(os.path.join(saveDir,newTxtName),'w') as fw:
fw.write(newtxtStr)
shutil.move(picPath,os.path.join(saveDir,newPicName))
# print(newPicName,'is done!')
if __name__ =='__main__':
allFilePath=getAllFilePath(r'E:\Numberdata\4')
# dealSampleList(allFilePath,r'E:\Numberdata\data')
n_total=len(allFilePath)
n_process=4 #8线程
#每段子列表长度
length=float(n_total)/float(n_process)
indices=[int(round(i*length)) for i in range(n_process+1)]
sublists=[allFilePath[indices[i]:indices[i+1]] for i in range(n_process)]
#生成进程池
p=Pool(n_process)
for i in sublists:
print("sublist len is {}".format(len(i)))
p.apply_async(dealSampleList, args=(i,r'E:\Numberdata\data'))
p.close()
p.join()
print("All done!")
希望本文所述对大家Python程序设计有所帮助。
来源:https://blog.csdn.net/sinat_24899403/article/details/87371271
标签:python,字符串
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python实现二维曲线拟合的方法
2021-08-26 12:38:01
python 多进程通信模块的简单实现
2021-06-13 08:21:32
python argparse的使用步骤(全网最全)
2023-06-14 01:13:45
![](https://img.aspxhome.com/file/2023/9/59289_0s.png)
详细分析vue表单数据的绑定
2023-07-02 16:27:51
![](https://img.aspxhome.com/file/2023/6/139666_0s.png)
MySQL 搭建MHA架构部署的步骤
2024-01-17 05:27:10
![](https://img.aspxhome.com/file/2023/5/111365_0s.png)
Python环境下安装使用异步任务队列包Celery的基础教程
2023-08-23 23:06:48
laravel 解决crontab不执行的问题
2023-11-15 01:45:18
![](https://img.aspxhome.com/file/2023/5/75875_0s.jpg)
Python字典深浅拷贝与循环方式方法详解
2022-08-04 08:52:25
![](https://img.aspxhome.com/file/2023/7/71317_0s.png)
简单的Vue SSR的示例代码
2023-07-02 17:08:46
![](https://img.aspxhome.com/file/2023/9/139949_0s.jpg)
测试框架JUnit VS TestNG对比分析
2023-02-11 02:44:02
关于交互设计在QQ秀赠送流程中的优化
2009-06-11 12:30:00
IBatis.net连接MySql 问题与故障的解决方案
2011-06-02 09:38:00
python中np.random.permutation函数实例详解
2021-10-13 16:18:35
![](https://img.aspxhome.com/file/2023/0/134700_0s.png)
Python导出DBF文件到Excel的方法
2023-03-12 20:50:15
一行CSS代码为网站加上奥运主题
2008-07-20 12:33:00
![](https://img.aspxhome.com/file/UploadPic/20087/20/2008720123826347s.png)
sql获取分组排序后数据的脚本
2024-01-20 09:07:58
详解pytorch tensor和ndarray转换相关总结
2023-08-18 20:03:51
![](https://img.aspxhome.com/file/2023/8/108168_0s.png)
Python实现功能完整的个人员管理程序
2021-03-26 02:31:15
![](https://img.aspxhome.com/file/2023/1/131061_0s.png)
可以用ASP生成由客户浏览器处理的客户端脚本吗?
2009-11-01 18:06:00
浅析Golang中的内存逃逸
2024-05-05 09:28:21