替换文本文件中的某些单词

时间:2014-07-03 10:19:07

标签: python

我正在尝试替换文本文件中的特定单词。我有一个文本文件(test.txt)文件的内容如下:

red red blue
green red blue
red

我希望用大写字母替换RED的每个实例。

到目前为止,我的编码是:

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

我真的不知道如何更换单词而且我确定我目前只计算单词的尝试是不好的。我将不胜感激任何帮助。

3 个答案:

答案 0 :(得分:1)

如果要替换文件中的内容,可以试试这个

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"))

答案 1 :(得分:0)

对于这类问题fileinput是正确的地方

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

答案 2 :(得分:0)

为避免替换red中未隔离的redness实例,请使用正则表达式

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)

例如,对于包含

的文件
the red redirect link

输出是:

replaced_content
>>> 'the RED redirect link'
count
>>> 1
相关问题