我一直想知道如何在查找和替换函数中让 Python 忽略双引号 (") 内的字符。我的代码是:
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 )
假设我们的文件(test.txt)有内容(这是我们的实际文本):
我喜欢你的代码"我喜欢你的代码"
我执行
findAndReplace('code','bucket',test.txt)
这会将以下内容写入我的文件:
我喜欢你的水桶"我喜欢你的水桶"
但是,我希望它跳过双引号部分并因此得到这个
我喜欢你的桶"我喜欢你的代码"
我应该在源代码中添加什么?
提前致谢
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)
假设你不能有嵌套引号...
如果你不需要处理引号内的引号,或者类似的东西,这很容易。您可以使用正则表达式来做到这一点。但是,由于我猜你不知道正则表达式(或者你一开始会使用它),让我们用简单的字符串方法来做:在引号字符上split
字符串,然后只replace
偶数子字符串,然后将其重新join
在一起:
for line in fileinput.input( fileToSearch ):
bits = line.split('"')
bits[::2] = [bit.replace(textToSearch, textToReplace) for bit in bits[::2]]
tempFile.write('"'.join(bits))