忽略查找和替换算法中引号中的字符

2024-06-14 21:18:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在想如何让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}$

它会将以下内容写入我的文件:

我喜欢你的水桶“我喜欢你的水桶”

但是,我希望它跳过双引号的部分,得到这个结果

我喜欢你的桶“我喜欢你的代码”

我应该在源代码中添加什么?在

提前谢谢


Tags: the代码linetempfileoldreplacefilerename
2条回答

如果你不需要处理引号内的引号,或者类似的事情,这是非常简单的。你可以用正则表达式来做。但是,由于我猜您不知道regexp(或者您可能会首先使用它),让我们用简单的strings方法来实现它:split您的字符串是引号字符,然后{}只包含偶数个子字符串,然后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))
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)

假设你不能有嵌套引号。。。在

相关问题 更多 >