2009-10-26 4 views
0

Новичок на Python .... помощи запрашиваемой следующей задачей :-)Python - RegExp - Изменение текстовых файлов

У меня есть дерево различных файлов, некоторые из них являются C исходный кодом. Я хотел бы изменить эти файлы C с помощью скрипта python.

код C имеет 4 DEFINES -

#define ZR_LOG0(Id, Class, Seveity, Format) 
#define ZR_LOG1(Id, Class, Seveity, Format, Attr0) 
#define ZR_LOG2(Id, Class, Seveity, Format, Attr0, Attr1) 
#define ZR_LOG3(Id, Class, Seveity, Format, Attr0, Attr1, Attr2) 

Существуют различные ZR_LOGn линии распространяются по всему исходному коду C.

Пример: ZR_LOG1 (1, LOG_CLASS_3, LOG_INFO, "hello world% d", 76);

Белые пространства (пробелы, табы) могут появляться в любом месте строки (между полями).

Задача сценария питона выглядит следующим образом:

  1. заменить любое поле «Id» (который является целочисленным типом, что мы не заботимся о своей первоначальной стоимости) с последовательным счетчиком. (Первая строка «LOG» ... мы встретимся в поле «Id», получим значение 0, следующее 1 и т. Д.)
  2. В отдельном выходном файле для каждой строки ZR_LOG мы будет создавать индексную строку в формате {NewID, Format}, Для приведенного выше примера получит:

    { 0, "hello world %d" }, 
    

Цените вашу помощь с ним ....


Я начал со следующего кода, вы можете либо посмотреть на него, либо проигнорировать его вообще.

''' 
Created on Oct 25, 2009 

@author: Uri Shkolnik 

The following version does find & replace LOG Ids for all 
C source files in a dir (and below) with sequential counter, 
The files are assumed to be UTF-8 encoded. 
(which works fine if they are ASCII, because ASCII is a 
subset of UTF-8) 
It also assemble new index file, composed from all new IDs and format fields 

''' 

import os, sys, re, shutil 

mydir= '/home/uri/proj1' 
searched_pattern0 = 'ZR_LOG0' 

def search_and_replace(filepath): 
    ''' replaces all string by a regex substitution ''' 
    backupName=filepath+'~re~' 

    print 'reading:', filepath 
    input = open(filepath,'rb') 
    s=unicode(input.read(),'utf-8') 
    input.close() 

    m = re.match(ur'''[:space:]ZR_LOG[0-3].*\(.*[0-9]{0,10},LOG_''', s) 
    print m 

def c_files_search(dummy, dirr, filess): 
    ''' search directories for file pattern *.c ''' 
    for child in filess: 
     if '.c' == os.path.splitext(child)[1] and os.path.isfile(dirr+'/'+child): 
      filepath = dirr+'/'+child 
      search_and_replace(filepath) 

os.path.walk(mydir, c_files_search, 3) 

ответ

1

Несколько моментов:

  • Вы можете соответствовать пробельные с '\ s'.
  • Группы захвата regexp полезны здесь.

Итак, я хотел бы сделать что-то вроде этого:

output = '' 
counter = 1 
for line in lines: 
    # Match only ZR_LOG lines and capture everything surrounding "Id" 
    match = re.match('^(.*\sZR_LOG[0-3]\s*\(\s*)' # group(1), before Id 
        'Id' 
        '(,.*)$', # group(2), after Id 
        line) 
    if match: 
     # Add everything before Id, the counter value and everything after Id 
     output += match.group(1) + str(counter) + match.group(2) 
     counter += 1 
     # And do extra logging etc. 
    else: 
     output += line 
+0

спасибо :-) было очень полезно – Uri