Search code examples
pythonsyntaxlexical-analysistranscoding

Ignore characters in quotation marks inside a find and replace algorithm


I have been wondering how I can make Python ignore characters inside double quotation marks (") in my find and replace function. My code is:

def findAndReplace(textToSearch, textToReplace,fileToSearch):
    oldFileName  = 'old-' + fileToSearch
    tempFileName = 'temp-' + fileToSearch
    tempFile = open( tempFileName, 'w' )
    for line in fileinput.input( fileToSearch ):
        tempFile.write( line.replace( textToSearch, textToReplace ) )
    tempFile.close()
    # Rename the original file by prefixing it with 'old-'
    os.rename( fileToSearch, oldFileName )
    # Rename the temporary file to what the original was named...
    os.rename( tempFileName, fileToSearch )

Suppose that our file (test.txt) has contents (THIS IS OUR ACTUAL TEXT):

I like your code "I like your code"

and I execute

findAndReplace('code','bucket',test.txt)

which will write the following to my file:

I like your bucket "I like your bucket"

However, I want it to skip the double-quoted part and get this as a result

I like your bucket "I like your code"

What should I add to my source code?

Thanks in advance


Solution

  • haystack = 'I like your code "I like your code"'
    needle = "code"
    replacement = "bucket"
    
    parts = haystack.split('"')
    for i in range(0,len(parts),2):
       parts[i] = parts[i].replace(needle,replacement)
    
    print '"'.join(parts)
    

    assuming you cannot have nested quotes ...