Search code examples
pythonstringaccumulator

Deleting every second occurence of a word in a txt file (Python)


I would like to delete some occurrences of the word "name" in a file but not others. I am guessing the best way to do this is to use some sort of accumulator pattern but I am not sure how to implement it.

So far I have:

f = open("old_text.txt")
number = f.read()
f.close

name_occurrence = (number.count("Courtney"))

I am just using 'Courtney' as an example of an actual name in the file. I would like to somehow delete every odd occurrence of the word "Courtney" but not the even ones i.e. as number.count iterates it assigns each instance of "Courtney" a number value and then some code deletes occurrences of the word "Courtney" that have a value of 1,3,5,7...

Thanks for your help,

Fluffy


Solution

  • Not tested, but you could try a regex like this:

    import re
    
    with open("old_text.txt") as f:
       txt = f.read()
       new_txt=re.sub(r'(\bCourtney\b.*?)(\s*\Courtney\b\s*)','\1',txt,re.S)
    

    If you want a dynamic string (i.e., that has a variable in it):

    import re
    
    name='Courtney'
    
    with open("old_text.txt") as f:
       txt = f.read()
       new_txt=re.sub(r'(\b{}\b.*?)(\s*\{}\b\s*)'.format(name,name),'\1',txt,re.S)