#! bin/usr/evn python # -*- coding:utf-8 -*- import os, sys, pyperclip import easygui as g import re file_name = 'tt3' with open(file_name, 'r', encoding='utf-8') as rf: old_text = rf.read() replace_code = r'''void test(void) { int a=10; char s[10]={0}; printf("a=%d,s=%s ",a,s); } ''' target_code_file='targetcode' with open(target_code_file,'r',encoding='utf-8') as rrrf: target_code_list= rrrf.readlines() # print(target_code_list) bracketsnum = replace_code.count('{') code_lines=replace_code.count(' ') pat = replace_code.split(' ')[0] # print(pat) # pat = pat.replace('(', '(') # pat = pat.replace(')', ')') # pat = pat.strip('{') # begin coding regex # repat = '{:s}{}{}{}{}'.format(pat, '.*{.+}', '{', '{:d}'.format(bracketsnum), '}') # patt = re.compile(repat, re.M | re.S) # print(patt) # result = re.findall(patt, old_text) pposi=0 posi=0 str_posilist=[] line_posilist=[] posi=old_text.find(pat,pposi) posil=old_text.count(' ',0,posi) str_posilist.append(posi) # 找出文位置 while posi !=-1: pposi = posi+1 posi=old_text.find(pat,pposi) str_posilist.append(posi) str_posilist.pop() # 找出行数 for po in str_posilist: posil=old_text.count(' ',0,po) line_posilist.append(posil) print(line_posilist) with open(file_name, 'r', encoding='utf-8') as rrf: old_lines=rrf.readlines() # print(old_lines) for line in line_posilist: lnum=line lnu=line+6 target=old_lines[lnum:lnu] target=target_code_list # print(old_lines) # target=old_lines[3:9] # print(target)