Question

I know I have already posted a similar question but this one is different and I have more code. Since the last question was voted down (although the answers were helpful to me) the mods could delete it so as not to clutter the forum.

Anyway, hopefully no one will be irritated by me asking another question trying to achieve my goal.

I am attempting to delete every odd occurrence of a name in a txt file. There are two parts to my question:

a) why do I get AttributeError: 'str' object attribute replace is read-only

b) am I going about this the right way using an accumulator pattern or is there a better way to do this? Someone else has already suggested using the re module but since I am a beginner and I don't know much about it, I am trying to avoid it for the time being.

This is my code so far:

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


new_file = open("new_text.txt", "w")

counter = 0
name = "Courtney"

for number in range(temp.count(name)):
    counter = +1 
    temp.find("Courtney")
    if counter % 2 == 0:
        pass
    else:
        temp.replace = ("Courteny", "")

new_file.write(temp)        
new_file.close

So I want to delete the first occurrence of 'Courtney' but not the second and so on until the end of the file. Then write the results to a new file.

Any help is much appreciated,

Fluffy

Was it helpful?

Solution

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


new_file = open("new_text.txt", "w")

counter = 0
name = "Courtney"

for number in range(temp.count(name)):
    counter = +1 
    temp.find("Courtney")
    if counter % 2 == 0:
        pass
    else:
        temp = temp.replace("Courteny", "")
#                         ^ No need for = sign here

new_file.write(temp)        
new_file.close

str.replace is a function, and takes in two parameters, first the thing you want to replace, and second the thing you want to replace it with. So, you do not need to assign anything here.

This is what your code should look like:

remember = []
with open('old_text.txt', 'r') as old:
    for var in old:
        remember += str(var).split(' ')[::2]
        remember += "\n"

with open('new_text.txt', 'w') as new:
    for var in remember:
        new.write(var + ' ')

print remember

OTHER TIPS

This should do it:

import collections
with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
  counts = collections.defaultdict(int)
  for line in infile:
    line = line.strip().split()
    for word in line:
      if not counts[word]%2:
        outfile.write(word + " ")
        counts[word] += 1
    outfile.write('\n')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top