我讀一個文件,我想換成兩個雙引號這樣之間的任何文本字符串之間:查找和替換報價
如果文件輸入:
Hi, I'm an example file! "Hi there example file."
"I'm mostly just here to get this quote to be colored!"
輸出應是:
Hi, I'm an example file! [color=x]"Hi there example file."[/color]
[color=x]"I'm mostly just here to get this quote to be colored!"[/color]
我已經寫了這三個模塊要做到這一點,前兩個工作,但最後卻沒有。
模塊1:
__author__ = 'Joker'
import os
import sys
import re
import fileinput
print ("Text to search for:")
textToSearch = ('" ')
print ("Text to replace it with:")
textToReplace = ('"[/color] ')
print ("File to perform Search-Replace on:")
fileToSearch = ("D:\Coding projects\post edit\post.txt")
tempFile = open(fileToSearch, 'r+')
for line in fileinput.input(fileToSearch):
if textToSearch in line :
print('Match Found')
else:
print('Match Not Found!!')
tempFile.write(line.replace(textToSearch, textToReplace))
tempFile.close()
input('\n\n Press Enter to exit...')
模塊2:
__author__ = 'Joker'
import os
import sys
import re
import fileinput
print ("Text to search for:")
textToSearch = (' "')
print ("Text to replace it with:")
textToReplace = (' [color=#66ccff]"')
print ("File to perform Search-Replace on:")
fileToSearch = ("D:\Coding projects\post edit\post.txt")
tempFile = open(fileToSearch, 'r+')
for line in fileinput.input(fileToSearch):
if textToSearch in line :
print('Match Found')
else:
print('Match Not Found!!')
tempFile.write(line.replace(textToSearch, textToReplace))
tempFile.close()
input('\n\n Press Enter to exit...')
模塊3:
__author__ = 'Joker'
import os
import sys
import re
import fileinput
print ("Text to search for:")
textToSearch = (r'\n"')
print ("Text to replace it with:")
textToReplace = (r'\n[color=#66ccff]"')
print ("File to perform Search-Replace on:")
fileToSearch = ("D:\Coding projects\post edit\post.txt")
tempFile = open(fileToSearch, 'r+')
for line in fileinput.input(fileToSearch):
if textToSearch in line :
print('Match Found')
else:
print('Match Not Found!!')
tempFile.write(line.replace(textToSearch, textToReplace))
tempFile.close()
input('\n\n Press Enter to exit...')
加成:是有辦法這三個模塊的功能結合變成一個?使用re
的regular expression
模塊爲
我已經在那裏輸入了。增加了輸出。 – TheJoker