[英]Ignore characters in quotation marks inside a find and replace algorithm
我一直想知道如何在我的查找和替換函數中讓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)
假設您不能使用嵌套引號...
如果您不需要處理引號內的引號或類似內容,這非常簡單。 您可以使用正則表達式來實現。 但是,由於我猜想您不知道regexp(否則您會首先使用它),讓我們使用簡單的字符串方法進行操作:在引號字符上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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.