zoukankan      html  css  js  c++  java
  • python学习笔记(1)--遍历txt文件,正则匹配替换文字

    遍历一个文件夹,把里面所有txt文件里的[]里的朗读时间删除,也就是替换为空。

     1 import os
     2 import re
     3 import shutil
     4 #os文件操作,re正则,shutil复制粘贴
     5 path1 = r"" #脚本
     6 path2 = r"" #mp3
     7 
     8 #for root1, dirs1, files1 in os.walk(path1):    #三个参数:分别返回1.父目录 2.所有文件夹名字(不含路径) 3.所有文件名字
     9 # for root2, dirs2, files2 in os.walk(path2):
    10 #     for i in range(0, len(files2)):
    11 #         num, other = files2[i].split('_', 1)
    12 #         num_root = os.path.join(root2, files2[i]) 
    13 #         #print (num)
    14 #         #C:UsersVideoEditorDesktop301_test1_一单元1_《为人民服务》1_预习1_音画课文
    15 #         num2 = r'\d_.*?单元\%s_.*?\1_预习\1_音画课文$' %num#这个地方好像是有贪婪匹配,加了“单元”后可用
    16 #         for root1, dirs1, files1 in os.walk(path1):
    17 #             if re.findall(num2, root1):
    18 #                 #shutil.copy(num_root, root1)
    19 #                 shutil.copy(num_root, root1+'\' + '录音.mp3')
    20 # print("导入成功!")
    21 path = r"C:UsersAdministratorDesktop人教6下TXT"
    22 for dirpath, dirnames, filenames in os.walk(path):
    23     for i in range(len(filenames)):
    24         filename = dirpath + "\" + filenames[i]
    25         # print(filename)
    26         lines = open(filename,'r').readlines()
    27         for i in range(len(lines)):
    28             # re.sub才能够匹配正则,replace只能替换字符串
    29             lines[i] = re.sub(r'[.*]','',lines[i])
    30             print(lines[i])
    31         open(filename,'w').writelines(lines)

    参考资料:

    https://zhidao.baidu.com/question/1989730234752380667.html

    https://zhidao.baidu.com/question/919138587511429259.html

  • 相关阅读:
    [leetCode]100.相同的树
    [leetCode]88.合并两个有序数组
    [leetCode]83.删除排序链表中的重复元素
    排序算法总结
    [leetCode]69. x 的平方根
    POJ 1151 Atlantis
    POJ 3468 A Simple Problem with Integers
    SGU 271 Book Pile
    POJ 2970 The lazy programmer
    FZU 2254 英语考试
  • 原文地址:https://www.cnblogs.com/Jacklovely/p/6395772.html
Copyright © 2011-2022 走看看