档案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作为字典,其中包含要搜索的字符串和要替换的字符串。我首先尝试匹配两个文件中的字符串,然后必须替换。但是第二部分没有给我任何匹配...我使用比较两个文件并在python中找到匹配的单词作为参考。
对于“第二部分”-无需使用正则表达式来替换中的文本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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句