python-通过正则表达式,提取txt文件中的特定内容,保存到新文件中


import easygui as g
import os
 
file_path=g.fileopenbox(default='*.*')
import numpy as np
import re
#file_path='E:/audio_data_hex_text.txt'

keywords = [
  "xxx pcm_read tick",
  "dler"
]
pattern = re.compile(r'xxx pcm_read tick:\d+')
pattern1 = re.compile(r'xxx pcm_read tick:\d+')
pattern2 = re.compile(r'YYYYruntime->.+$')
patterns = [
    pattern1,
    pattern2
]    

isIn = 0

j = 0

def genTempFilePath(old_file_path):
    file=os.path.splitext(old_file_path)
    filename,type=file
    new_file_path = filename + '.tmp'+ type
    #print(new_file_path)
    return new_file_path

file_path_temp = genTempFilePath(file_path)

with open(file_path, 'r', errors='ignore') as txtfile:  
    lines=txtfile.readlines()
txtfile.close()
print(file_path_temp)
with open(file_path, 'r') as txtfile:
    txtfile.close()

with open(file_path_temp, 'w+') as newtxtfile:
    machLines=0
    machPattern=0
    oldFileLines=len(lines)
    #print(lines)
    for i,rows in enumerate(lines):
        #print('scanning line: ',i)
        #print(rows)
        
        for j,pattern in enumerate(patterns):
            result = pattern.findall(rows)
            #searchObj =  re.search(pattern, rows)
            #if searchObj:
            #    print(searchObj.group())
            #    newtxtfile.writelines(searchObj.group()+'\n')
            #else:
            #    print('search null')
            #print("find:")

            #print('type is', type(result))
            #print(result)
            if (result):
                machLines +=1
                isIn = 1
            if (isIn == 1):
                result_list_len=len(result)
                machPattern += result_list_len
                k=0
                for k in range(0, len(result)):
                    #print('result',k,result[k])    
                    newtxtfile.writelines(result[k]+'\n')
                continue                         
    print('old file lines:',oldFileLines)
    print('find mach lines:',machLines)
    print('find mach patterns:',machPattern)  
newtxtfile.close()

 

  • 1
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值