Pregunta

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

¿Fue útil?

Solución

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 ...

Otros consejos

If you don't need to handle quotes inside quotes, or anything like that, this is pretty easy. You could do it with regular expressions. But, since I'm guessing you don't know regexp (or you would have used it in the first place), let's do it with simple strings methods: split your string on quote characters, then replace only the even substrings, then join it back together:

for line in fileinput.input( fileToSearch ):
    bits = line.split('"')
    bits[::2] = [bit.replace(textToSearch, textToReplace) for bit in bits[::2]]
    tempFile.write('"'.join(bits))
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top