文件1:
$def String_to_be_searched (String to be replaced with)
文件2:
..... { word { ${String to be searched} } # each line in File 2 is in this format
..... { word { ${String} } # This line need not be replaced. Only lines which matches the string in file 1 needs to be replaced
我想替换要搜索的"字符串"在文件2中用"字符串替换为"从文件1开始,文件2的每一行都有"要搜索的字符串"在里面。
我的代码:
def labelVal(line):
return line[line.find('(') + 1: line.rfind(')')]
for line in File 1:
Label = {}
line = line.strip()
if line.startswith('$def'):
labelKeys = line .split()[1]
#print labelKeys
labelValues = labelVal(line)
#print labelValues
Label[labelKeys] = labelValues
#print Label
outfile = open('path to file','w')
for line in File 2:
match = re.findall(r'\$\{(\w+)\}', line) # Here I am searching for the pattern ${String to be searched}
if match:
print match.group()
远期输出:
我将Label作为字典,包含要搜索的字符串和要替换的字符串。我首先尝试匹配两个文件中的字符串然后我必须替换。但第二部分没有给我任何匹配......我使用compare two file and find matching words in python作为参考。
答案 0 :(得分:0)
对于"第二部分" - 替换File 2
中的文本不需要正则表达式。只需阅读整个文件,然后使用str
方法replace
。
with open('tobefixed.txt') as f:
data = f.read()
for search_txt, replacement_txt in Label.iteritems():
data = data.replace(search_txt, replacement_txt)
with open('fixed.txt', 'w') as f:
f.write(data)
如果您想使用re
模块,请使用re.sub
:
for search_txt, replacement_txt in Label.iteritems():
data = re.sub(search_txt, replacement_txt, data)
print data
对于"第一部分" - 在Label
循环的每次迭代中创建一个新字典for
。您应该只创建一个包含所有defs
的字典;
with open('defs.txt') as f:
Label = {}
for line in f:
line = line.strip()
if line.startswith('$def'):
labelKeys = line .split()[1]
labelValues = labelVal(line)
Label[labelKeys] = labelValues