简体   繁体   中英

Replace exact match word with specific string in python

I am completely new to Python and this is my first script to replace word.

my file test.c contains following two lines

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

Now I want to replace printf and fprintf by //printf and //fprintf respectively.

Here is what I have tried

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()

But using this I got

fprintf to //f//printf which is wrong.

For the solution have looked this answer but not able to fit it in my script.

Anyone have idea how can I fix it?

Basically you want to convert printf to //printf and fprintf to //fprintf. If that's the case then this might work, try it out.

  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()

dict in python is not ordered. so you cannot guarantee print or fprintf will be picked up first while traversing dict in the following line:

for src, target in replacements.iteritems():

In the current case, print looks to be picked first thats why you are facing the issue. In order to avoid the issue, either use orderdict or keep list of dicts for replacements .

Here's what it's doing. The dictionaries are not ordered (as you may think they are) so the fprintf replacement actually comes first and then it replaces the printf portion of it. Sequence:

fprintf -> //fprintf -> //f//printf
(?=\bprintf\b|\bfprintf\b)

Use re.sub from re module.See demo.

https://regex101.com/r/pM9yO9/18

import re
p = re.compile(r'(?=\bprintf\b|\bfprintf\b)', re.IGNORECASE | re.MULTILINE)
test_str = "printf(\"\nReboot not supported. Exiting instead.\n\");\nfprintf(stderr, \"FATAL: operation not supported!\n\");"
subst = "//"

result = re.sub(p, subst, test_str)

Pass your file line by line and print output to different file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM