後發到了比賽,這是我實施的sed在Python:在foo.txt的
sed('foo', 'bar', "foo.txt")
將與 '酒吧' 替換所有 '富':
import re
import shutil
from tempfile import mkstemp
def sed(pattern, replace, source, dest=None, count=0):
"""Reads a source file and writes the destination file.
In each line, replaces pattern with replace.
Args:
pattern (str): pattern to match (can be re.pattern)
replace (str): replacement str
source (str): input filename
count (int): number of occurrences to replace
dest (str): destination filename, if not given, source will be over written.
"""
fin = open(source, 'r')
num_replaced = count
if dest:
fout = open(dest, 'w')
else:
fd, name = mkstemp()
fout = open(name, 'w')
for line in fin:
out = re.sub(pattern, replace, line)
fout.write(out)
if out != line:
num_replaced += 1
if count and num_replaced > count:
break
try:
fout.writelines(fin.readlines())
except Exception as E:
raise E
fin.close()
fout.close()
if not dest:
shutil.move(name, source)
例子
sed('foo', 'bar', "foo.txt", "foo.updated.txt")
將取代在「foo.txt的」酒吧'所有「富」並保存結果「foo.updated.txt」。
sed('foo', 'bar', "foo.txt", count=1)
只會取代「富」與「酒吧」的第一次出現,並將結果保存在原始文件「foo.txt的」
你sed的例子並不等同於你實際上是試圖做。 –
所以在bash中,我正在這樣做,它正在工作,但超級慢...... – user1601716
你實際上可以使用'subprocess'命令在python中運行sed。 – karthikr