我正在尝试在 Linux 上编译过于干净的 C++ 文件。具体来说,我试图用 python 脚本(我必须使用 python)在 #include 语句中将反斜杠“\”替换为斜杠“/”。 不幸的是,脚本删除了除了最后一个括号之外的几乎所有内容:
}
我正在使用这个脚本:
import os
import re
for dirpath, dirnames, filenames in os.walk(".\Source", topdown=True):
for file in filenames:
file = os.path.join(dirpath, file)
tempfile = file + ".bak"
with open(tempfile, "w") as target:
with open(file) as source:
for line in source:
if "#include" in line:
re.sub("\\\\", "/", line)
target.write(line)
os.remove(file)
os.rename(tempfile, file)
编辑: 在实现 Simon Fraser 的建议后,脚本现在运行良好。它看起来像这样:
import os
import re
for dirpath, dirnames, filenames in os.walk(".\Source", topdown=True):
for file in filenames:
file = os.path.join(dirpath, file)
tempfile = file + ".bak"
with open(tempfile, "w") as target:
with open(file) as source:
for line in source:
if "#include" in line:
line = re.sub(r"\\", "/", line)
target.write(line)
os.remove(file)
os.rename(tempfile, file)
最佳答案
考虑这个部分:
for line in source:
if "#include" in line:
re.sub("\\\\", "/", line)
target.write(line)
在 for
循环中,没有任何内容写入文件 target
。一旦 for
循环结束,line
的最后一个值被写出,这可能就是为什么你只得到最后一个 的原因输出。
如果您将 target.write
移动到 for
循环中,事情应该会起作用。 re.sub
还返回 新值而不是替换 line
,因此您也需要在那里进行变量赋值。
for line in source:
if "#include" in line:
line = re.sub("\\\\", "/", line)
target.write(line)
字符串也有一个.replace
方法,可能会更快:
for line in source:
if '#include' in line:
line = line.replace('\\','/')
target.write(line)
关于python - python中的正则表达式删除太多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45346047/