python实现修改固定模式的字符串内容操作示例

yipeiwu_com6年前Python基础

本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《Python字符串操作技巧汇总》、《Python数据结构与算法教程》、《Python列表(list)操作技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

python中is与双等于号“==”的区别示例详解

前言 在开始本文之前,首先要知道Python中对象包含的三个基本要素,分别是:id(身份标识)、python type()(数据类型)和value(值)。is和==都是对对象进行比较判断...

pytorch多GPU并行运算的实现

Pytorch多GPU运行 设置可用GPU环境变量。例如,使用0号和1号GPU' os.environ["CUDA_VISIBLE_DEVICES"] = '0,1' 设置模型...

python正则表达式re之compile函数解析

re正则表达式模块还包括一些有用的操作正则表达式的函数。下面主要介绍compile函数。 定义: compile(pattern[,flags] ) 根据包含正则表达式的字符串创...

Python列表解析配合if else的方法

用习惯列表解析之后会觉得超级酷,所以在尝试使用列表解析,把循环什么的写在一行里面。使用if的时候什么时候必须要有else,什么时候可以没有else一直没搞明白,直到今天!待我缓缓道来:...

widows下安装pycurl并利用pycurl请求https地址的方法

widows下安装pycurl并利用pycurl请求https地址的方法

步骤一:下载对应的CURL压缩包并在windows上配置好环境变量 进入CURL官网下载对应的windows压缩包。地址:点击打开链接 把下载好的压缩包解压到自己喜欢的一个目录下,我暂...