English 中文(简体)
Python regular expression matching a multiline block of text but not replacing it
原标题:

Ok so i have this piece of code:

def findNReplaceRegExp(file_name, regexp, replaceString, verbose=True, confirmationNeeded=True):
   Replaces the oldString with the replaceString in the file given,
   returns the number of replaces
   
    # initialize local variables
    cregexp = re.compile(regexp, re.MULTILINE | re.DOTALL)
    somethingReplaced = True
    ocurrences = 0
    isAborted = False

    # open file for read
    file_in = open(file_name,  r )
    file_in_string = file_in.read()
    file_in.close()

    while somethingReplaced:
        somethingReplaced = False
        # if the regexp is found
        if cregexp.search(file_in_string):
            # make the substitution
            replaced_text = re.sub(regexp, replaceString, file_in_string)
            if verbose == True:
                # calculate the segment of text in which the resolution will be done

                # print the old string and the new string
                print  -   + file_in_string
                print  +   + replaced_text
                if confirmationNeeded:
                    # ask user if this should be done
                    question = raw_input( Accept changes? [Yes (Y), No (n), Abort (a)]  )
                    question = string.lower(question)
                    if question ==  a :
                        isAborted = True
                        print "Aborted"
                        break
                    elif question ==  n :
                        pass
                    else:
                        file_in_string = replaced_text
                        somethingReplaced = True
                        ocurrences = ocurrences + 1
            else:
                file_in_string = replaced_text
                somethingReplaced = True
                ocurrences = ocurrences + 1

    # if some text was replaced, overwrite the original file
    if ocurrences > 0 and not isAborted:
        # open the file for overwritting
        file_out = open(file_name,  w )
        file_out.write(file_in_string)
        file_out.close()
        if verbose: print "File " + file_name + " written"

And this file

CMC_SRS T10-24400: DKU Data Supply: SN Time Break-In Area
CMC_SRS T10-24401: DKU Data Supply: SN Transponder Enable Area
CMC_SRS T10-24402: DKU Data Supply: SN Adjust Master Slave Area
CMC_SRS T10-24403: DKU Data Supply: SN ATEC Area
CMC_SRS T10-24404: DKU Data Supply: SN PTEC Area
CMC_SRS T10-25449: DKU Data Supply: SN Self Init Area
CMC_SRS T10-24545: DKU Data Supply: SN Time Area
CMC_SRS T10-4017: RFI display update
CMC_SRS T10-6711: Radio Interface to PLS Equipment
CMC_SRS T10-21077: Safety Requirements: Limit FM Power

When i call the procedure with this file and these parameters: regexp=24403.*24404 replace=TESTSTRING

i get a coincidence (it matches and questions what to do) but when its time to replace nothing happens... Whats wrong??

最佳回答

You re finding with cregexp, which has the multiline option set, but then replacing with regexp, which may or may not.

问题回答

暂无回答




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签