python 自带 re bug 推荐使用 regex

报错 re.error: bad escape \L at

原因 python 自带的 re 有问题
修改成 regex 即可

安装 regex

pip install regex

使用

import regex as re

关键替换代码 使用 re.sub

str_des_file_0 = re.sub('(?s)<name>.*</name>', r"<name>w</name>", str_file)
images_dir_path = "D:/voc2007/JPEGImages/"
image_path = os.path.join(images_dir_path, i)
path_str = r"<path>{}</path>".format(image_path)
# print(path_str)
str_des_file_1 = re.sub('(?s)<path>.*</path>', path_str, str(str_des_file_0))

替换完整代码

import os, shutil
import regex as re


def mv_floder(path):
  dir_abs_path = os.path.abspath(path)
  res_dir = os.path.dirname(dir_abs_path)

  res_dir = os.path.join(res_dir, "voc2007")
  if os.path.exists(res_dir):
    shutil.rmtree(res_dir)

  os.mkdir(res_dir)

  annotations_dir = os.path.join(res_dir, "Annotations")
  if not os.path.exists(annotations_dir):
    os.mkdir(annotations_dir)

  JPEGImages_dir = os.path.join(res_dir, "JPEGImages")
  if not os.path.exists(JPEGImages_dir):
    os.mkdir(JPEGImages_dir)

  print(dir_abs_path)
  for root, y, files in os.walk(dir_abs_path):
    for i in files:
      file_path = os.path.join(root, i)

      if root.find("annotations") != -1 or root.find("Annotations") != -1:
        des_file_path = os.path.join(res_dir, "Annotations")
        des_file_path = os.path.join(des_file_path, i)

        with open(file_path, "r", encoding="utf8") as f:
          str_file = f.read()
          # print(str_file)
          str_des_file_0 = re.sub('(?s)<name>.*</name>', r"<name>w</name>", str_file)
          images_dir_path = "D:/voc2007/JPEGImages/"
          image_path = os.path.join(images_dir_path, i)
          path_str = r"<path>{}</path>".format(image_path)
          # print(path_str)
          str_des_file_1 = re.sub('(?s)<path>.*</path>', path_str, str(str_des_file_0))
          with open(des_file_path, "w", encoding="utf8") as f_des:
            # print(str_des_file)
            f_des.write(str_des_file_1)

        # shutil.copyfile(file_path, des_file_path)
      if root.find("JPEGImages") != -1:
        des_file_path = os.path.join(res_dir, "JPEGImages")
        des_file_path = os.path.join(des_file_path, i)
        shutil.copyfile(file_path, des_file_path)


if __name__ == "__main__":
  mv_floder("./20200903-1jieguo")
  mv_floder("./20200903-2")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yuemake999

请我喝茶呗

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值