我是Python的新手。我希望能够打开一个文件,并通过Python替换给定替换的某些单词的每个实例。例如,用'bo'替换每个单词'zero',用'bob'替换'temp',用'nothing'代替'garbage'。
我第一次开始使用它:
for line in fileinput.input(fin):
fout.write(line.replace('zero', '0'))
fout.write(line.replace('temp','bob'))
fout.write(line.replace('garbage','nothing'))
但我不认为这是一种甚至是远程正确的方法。然后,我考虑使用if语句来检查行是否包含这些项,如果是,则替换该行包含哪一行,但是根据我所知的Python,这也不是真正理想的解决方案。我很想知道最好的方法是什么。提前谢谢!
答案 0 :(得分:72)
这应该这样做
replacements = {'zero':'0', 'temp':'bob', 'garbage':'nothing'}
with open('path/to/input/file') as infile, open('path/to/output/file', 'w') as outfile:
for line in infile:
for src, target in replacements.iteritems():
line = line.replace(src, target)
outfile.write(line)
编辑:要解决Eildosa's comment,如果您想在不写入其他文件的情况下执行此操作,那么您最终必须将整个源文件读入内存:
lines = []
with open('path/to/input/file') as infile:
for line in infile:
for src, target in replacements.iteritems():
line = line.replace(src, target)
lines.append(line)
with open('path/to/input/file', 'w') as outfile:
for line in lines:
outfile.write(line)
修改:如果您使用的是Python 3.x,请使用replacements.items()
代替replacements.iteritems()
答案 1 :(得分:7)
我可能会考虑使用dict
和re.sub
来实现这样的目标:
import re
repldict = {'zero':'0', 'one':'1' ,'temp':'bob','garage':'nothing'}
def replfunc(match):
return repldict[match.group(0)]
regex = re.compile('|'.join(re.escape(x) for x in repldict))
with open('file.txt') as fin, open('fout.txt','w') as fout:
for line in fin:
fout.write(regex.sub(replfunc,line))
这对replace
略有优势,因为重叠匹配会更加健壮。
答案 2 :(得分:6)
如果您的文件很短(甚至不是很长),您可以使用以下代码段替换文字:
# Replace variables in file
with open('path/to/in-out-file', 'r+') as f:
content = f.read()
f.seek(0)
f.truncate()
f.write(content.replace('replace this', 'with this'))
答案 3 :(得分:4)
基本方法是
read()
,data = data.replace()
根据您的需要随时write()
。如果您一次读取或写入整个数据,或者更小的部分由您自己决定。您应该依赖于预期的文件大小。
read()
可以替换为文件对象的迭代。
答案 4 :(得分:2)
更快的写作方式是...
in = open('path/to/input/file').read()
out = open('path/to/input/file', 'w')
replacements = {'zero':'0', 'temp':'bob', 'garbage':'nothing'}
for i in replacements.keys():
in = in.replace(i, replacements[i])
out.write(in)
out.close
这消除了其他答案提出的大量迭代,并将加快更长文件的处理速度。
答案 5 :(得分:0)
从标准输入读取,按如下方式编写'code.py':
import sys
rep = {'zero':'0', 'temp':'bob', 'garbage':'nothing'}
for line in sys.stdin:
for k, v in rep.iteritems():
line = line.replace(k, v)
print line
然后,使用重定向或管道(http://en.wikipedia.org/wiki/Redirection_(computing))
执行脚本python code.py < infile > outfile
答案 6 :(得分:0)
这是我刚才使用的一个简短的例子:
如果:
fp = open("file.txt", "w")
然后:
fp.write(line.replace('is', 'now'))
// "This is me" becomes "This now me"
不
line.replace('is', 'now')
fp.write(line)
// "This is me" not changed while writing