我正在打开文件并搜索特定单词以替换文件中该单词的最后2次出现。
我已打开文件并尝试替换,但它正在替换前两次出现的文件。我想替换最后两次出现的地方
s = open("mount.txt").read()
s = s.replace('mickey', 'minnie',2)
f = open("mount.txt", 'w')
f.write(s)
f.close()
这只是文本。实际文字不同。
#mount.txt#
I'm mickey. minnie is my friend.
mickey is the good name given by my parents.
mickey loves to play cricket.
Where as his parents doesn't like Mickey's habit.
#Replaces text[mount.txt]#
I'm mickey. minnie is my friend.
Mickey is the good name given by my parents.
minnie loves to play cricket.
Where as his parents doesn't like minnie's habit.
答案 0 :(得分:2)
s = open("mount.txt").read()
sr = s.rsplit('mickey', 2)
s = 'minnie'.join(sr)
f = open("mount.txt", 'w')
f.write(s)
f.close()
答案 1 :(得分:0)
这是一个可能的解决方案。注意:此版本区分大小写,因此mickey
和Mickey
不能被视为相同;但是如果您需要不区分大小写的替换,则此代码至少会为您提供一个完整解决方案的可能方向。
def func(word_to_search, replacement_word, num_replacements):
with open('test.txt') as f:
old_lines = f.readlines()
new_lines = []
counter = 0
for line in reversed(old_lines): # iterate in reverse order
if counter < num_replacements:
# only check if 'num_replacements' has not been reached yet
while word_to_search in line:
line = line.replace(word_to_search, replacement_word, 1)
counter += 1
if counter >= num_replacements:
# exit while loop because 'num_replacements' has been reached
break
new_lines.append(line)
# reverse list again to get original order
new_lines = list(reversed(new_lines))
with open('test2.txt', 'w') as f:
f.writelines(new_lines)
if __name__ == '__main__':
func(
word_to_search='mickey',
replacement_word='MINNIE',
num_replacements=2)
输入:
I'm mickey. minnie is my friend.
mickey is the good name given by my parents.
mickey loves to play cricket.
Where as his parents doesn't like Mickey's habit.
输出(最后一行上的Mickey
未被替换,因为它不是全部小写):
I'm mickey. minnie is my friend.
MINNIE is the good name given by my parents.
MINNIE loves to play cricket.
Where as his parents doesn't like Mickey's habit.