使用 Python 替换文件中的文本
- 2025-03-21 09:05:00
- admin 原创
- 45
问题描述:
我是 Python 新手。我希望能够打开一个文件并通过 Python 将某些单词的每个实例替换为给定的替换项。例如,将每个单词“zero”替换为“0”,将“temp”替换为“bob”,将“garbage”替换为“nothing”。
我第一次开始使用这个:
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 的了解来看,这也不是真正的理想解决方案。我很想知道最好的方法是什么。提前谢谢!
解决方案 1:
这应该可以
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.items():
line = line.replace(src, target)
outfile.write(line)
编辑:为了解决Eildosa 的评论,如果您想在不写入其他文件的情况下执行此操作,那么您最终将不得不将整个源文件读入内存:
lines = []
with open('path/to/input/file') as infile:
for line in infile:
for src, target in replacements.items():
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 2.x,replacements.iteritems()
请使用replacements.items()
解决方案 2:
如果您的文件很短(或者甚至不是很长),您可以使用以下代码片段来替换文本:
# 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:
我可能会考虑使用dict
andre.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
因为它对于重叠匹配更加稳健。
解决方案 4:
根本方法是
read()
,data = data.replace()
根据需要,然后write()
。
是否一次性读写全部数据或分成几个小部分读写取决于您。您应该根据预期的文件大小来决定。
read()
可以用文件对象的迭代来代替。
解决方案 5:
更快的书写方式是......
finput = 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():
finput = finput.replace(i, replacements[i])
out.write(finput)
out.close
这消除了其他答案建议的许多迭代,并将加快较长文件的处理速度。
解决方案 6:
从标准输入读取,写入“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
解决方案 7:
这是我刚刚使用的一个简短而简单的例子:
如果:
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
扫码咨询,免费领取项目管理大礼包!