我一直在想如何让Python忽略find and replace函数中双引号(“)内的字符。我的代码是:
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 )
假设我们的档案(测试.txt)有内容(这是我们的实际文本):
我喜欢你的代码“我喜欢你的代码”
我执行
^{pr2}$它会将以下内容写入我的文件:
我喜欢你的水桶“我喜欢你的水桶”
但是,我希望它跳过双引号的部分,得到这个结果
我喜欢你的桶“我喜欢你的代码”
我应该在源代码中添加什么?在
提前谢谢
如果你不需要处理引号内的引号,或者类似的事情,这是非常简单的。你可以用正则表达式来做。但是,由于我猜您不知道regexp(或者您可能会首先使用它),让我们用简单的strings方法来实现它:}只包含偶数个子字符串,然后
split
您的字符串是引号字符,然后{join
将其组合起来:假设你不能有嵌套引号。。。在
相关问题 更多 >
编程相关推荐