一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

python如何实现修改固定模式的字符串内容 python实现修改固定模式字符串内容代码

时间:2019-12-30 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下python实现修改固定模式字符串内容代码,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

说明

字符串模式是开头可能有空格,之后可能存在多个小数点,然后后面跟着一个数字,数字可能是小数,数字后可能存在空格。

任务要求删去开头的小数点,如下:

" …78 " 修改为" 78 "

" …7.889 " 修改为" 7.889 "

“.9.8"修改为"9.8”

代码示例

注意这里正则的模式和分组的用法

import os
import re
testStr=r"...7.88 "
pattern=re.compile(r'(?P *)(?P.*)(?Pd+.?S*)(?P *)')
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 *)(?P.*)(?Pd+.?S*)(?P *)')
  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:Numberdatawrong.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:Numberdata4')
  # dealSampleList(allFilePath,r'E:Numberdatadata')
  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:Numberdatadata'))
  p.close()
  p.join()
  print("All done!")

热门栏目