可能重复:
在python中替换四个字母的单词
对于作业,我需要打开一个文件,将所有四个字母的单词替换为“xxxxxx”,然后将文本写入一个新文件。
这是给出的原始文件中的文件文本:
The 3 lines in this file end with the new line character.
There is a blank line above this line.
这是我到目前为止所拥有的:
def censor(filename):
infile=open(filename,"r")
content=infile.read()infile.close()
outfile = open("censored.txt","w")
content=content.replace("this","xxxxxx")
content=content.replace("file","xxxxxx")
content=content.replace("with","xxxxxx")
content=content.replace("line","xxxxxx")
outfile.write(content)
outfile.close()
这是结果:
The 3 xxxxxxs in xxxxxx xxxxxx end xxxxxx the new xxxxxx character.
There is a blank xxxxxx above xxxxxx xxxxxx.
我很难让“line”而不是“lines”改变,因为此刻“lines”正在变为“xxxxxxs”。
有谁知道这样做的特定方法?是否需要 if 语句?