[英]Replace exact match word with specific string in python
我對Python完全陌生,這是我第一個替換word的腳本。
我的文件test.c
包含以下兩行
printf("\nReboot not supported. Exiting instead.\n");
fprintf(stderr, "FATAL: operation not supported!\n");
現在,我想分別用//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()
但是使用這個我得到了
fprintf
到//f//printf
這是錯誤的。
對於解決方案,已經找到了這個答案,但無法將其放入我的腳本中。
有人知道我該如何解決嗎?
基本上,您想將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
或fprintf
:
for src, target in replacements.iteritems():
在當前情況下,首先要選擇print
,這就是您面對此問題的原因。 為了避免出現此問題,請使用orderdict或保留用於replacements
的字典列表。
這就是它在做什么。 字典沒有排序(您可能會認為是有序的),因此實際上首先出現了fprintf
替換,然后替換了它的printf
部分。 序列:
fprintf -> //fprintf -> //f//printf
(?=\bprintf\b|\bfprintf\b)
使用re.sub
從重新module.See演示。
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)
逐行傳遞文件,然后將輸出打印到其他文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.