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()

 

發佈了28 篇原創文章 · 獲贊 12 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章