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

Jay*_*hoi 2 python

我是Python的新手,这是我第一个替换word的脚本.

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

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

现在我要替换printf并fprintf通过//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()
Run Code Online (Sandbox Code Playgroud)

但是我得到了这个

fprintf到//f//printf这是错误的.

对于解决方案已经看了这个答案,但不能适应我的脚本.

任何人都知道如何解决它?

小智 5

基本上你想将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()
Run Code Online (Sandbox Code Playgroud)