-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.

1
  • 1
    You can try txt.read().replace("red","RED") assuming you dont have any words containing red Commented Jul 3, 2014 at 10:24

3 Answers 3

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")) 
Sign up to request clarification or add additional context in comments.

2 Comments

This will change the red redirect link to the RED REDirect link.
@BurhanKhalid My answer solves it, if that is an issue for the OP
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 

Comments

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.