我读一个文件,我想换成两个双引号这样之间的任何文本字符串之间:查找和替换报价
如果文件输入:
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