用python中的特定字符串替换完全匹配的单词 - python

我对Python完全陌生,这是我第一个替换word的脚本。

我的文件test.c包含以下两行

printf("\nReboot not supported.  Exiting instead.\n");
fprintf(stderr, "FATAL:  operation not supported!\n");

现在,我想分别用printffprintf替换//printf//fprintf

这是我尝试过的

infile = open('path\to\input\test.c')
outfile = open('path\to\output\test.c', 'w')

replacements = {'printf':'//printf', 'fprintf':'//fprintf'}

for line in infile:
    for src, target in replacements.iteritems():
        line = line.replace(src, target)
    outfile.write(line)
infile.close()
outfile.close()

但是使用这个我得到了

fprintf//f//printf这是错误的。

对于解决方案,已查看此answer,但无法将其放入我的脚本中。

有人知道我该如何解决吗?

python大神给出的解决方案

基本上,您想将printf转换为// printf,将fprintf转换为// fprintf。如果是这种情况,则可能会起作用,请尝试一下。

  outfile = open("test.c", 'r')
  temp = outfile.read()
  temp = re.sub("printf", "//printf", temp)
  temp = re.sub("f//printf", "//fprintf", temp)
  outfile.close()
  outfile = open("test.c","w")
  outfile.write(temp)
  outfile.close()