【发布时间】:2016-03-05 07:56:42
【问题描述】:
我正在读取一个文件,我想替换出现在两个双引号之间的任何文本,如下所示:
如果文件输入是:
嗨,我是一个示例文件! “你好,示例文件。”
“我主要是为了给这句话涂上颜色!”
输出应该是:
嗨,我是一个示例文件! [color=x]“你好,示例文件。”[/color]
[color=x]“我主要是为了给这句话涂上颜色!”[/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...' )
奖励:有没有办法将这三个模块的功能合二为一?
【问题讨论】:
-
我已经在里面输入了。添加了输出。感谢您的提醒(我确实阅读了如何提问部分。)