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

2024-10-01 15:29:24 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

现在我想把printf和{}分别替换为//printf和{}。在

这是我尝试过的

^{pr2}$

但用这个我得到了

fprintf到{},这是错误的。在

因为解决方案已经看过了answer,但无法将其放入我的脚本中。在

有人知道我该怎么修吗?在


Tags: 文件test脚本stderrnotoperationwordsupported
3条回答

基本上,您需要将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()

python中的dict没有顺序。因此,您不能保证print或{}在以下行遍历dict时首先被选中:

for src, target in replacements.iteritems():

在当前的情况下,print看起来是首先被选中的,这就是您面临这个问题的原因。为了避免这个问题,请使用orderdict或保留{}的dict列表。在

这就是它在做什么。字典并不是按顺序排列的(正如您可能认为的那样),因此fprintf替换实际上首先出现,然后替换其中的printf部分。顺序:

fprintf -> //fprintf -> //f//printf

相关问题 更多 >

    热门问题