-2

I am trying to replace specific words within a text file. I have a text file (test.txt) the content of the file is as follows:

red red blue
green red blue
red

I wish to replace each instance of red with RED in capitals.

My coding so far is this:

print "What file would you like to read?",
filename = raw_input()

txt = open(filename)
print txt.read()

import re

x=len(re.findall('red', open(filename).read()))

print "The total number of the word 'red' is: %r" % x

I really have no idea how I would go about replacing words and i'm sure my current attempt at just counting the word is bad. I would appreciate any help.

3 Answers3

1

If you want to replace the content in file, you can try this

content = []
filename='foo.txt'
with open(filename, 'r') as read_file:
    content = read_file.readlines()

with open(filename, 'w') as write_file:
    for line in content:
        write_file.write(line.replace("red", "RED"))
xecgr
  • 5,095
  • 3
  • 19
  • 28
0

For this kind of problem fileinput is right place

import fileinput
import sys
count = 0
for line in fileinput.input(["a.txt"], inplace=True, backup='.bak'):
    if 'red' in line:
        no_of_red=line.count('red')
        sys.stdout.write(line.replace('red','RED'))
        count += no_of_red
    else:
        sys.stdout.write(line)

print "The total number of the word 'red' is: %r" % count
sundar nataraj
  • 8,524
  • 2
  • 34
  • 46
0

To avoid replacing not isolated instance of red such as in redness you should use a regular expression

import re
pattern = re.compile(r'\bred\b')

print "What file would you like to read?",
filename = raw_input()

with open(filename, 'r') as f:
    content = f.read()
    replaced_content, count = pattern.subn('RED', content)

For example, for a file containing

the red redirect link

the output is:

replaced_content
>>> 'the RED redirect link'
count
>>> 1
Germano
  • 2,452
  • 18
  • 25