使用Python替换文件中最后两个特定单词的出现

2024-04-26 12:14:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在打开文件并搜索特定单词,以替换文件中该单词的最后2个匹配项。你知道吗

我已打开文件并尝试替换,但它正在替换前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.

Tags: 文件thename文本friendtxtismy
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()

这里有一个可能的解决办法。注意:这个版本是区分大小写的,所以mickeyMickey不被视为相同的;但是如果您需要不区分大小写的替换,这个代码至少会为您指明一个完整解决方案的可能方向。你知道吗

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.

相关问题 更多 >