文件1:
$def String_to_be_searched (String to be replaced with)
文件2:
^{pr2}$我想将文件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()
目前产量:
我有一个字典的标签,有要搜索的字符串和要替换的字符串。我首先尝试匹配两个文件中的字符串,然后我必须替换。但第二部分没有给我任何匹配。。。我用compare two file and find matching words in python这个作为参考。在
对于“第二部分”,不需要正则表达式来替换
File 2
中的文本。只需读取整个文件并使用str
方法replace
。在如果要使用
^{pr2}$re
模块,请使用re.sub
:对于“第一部分”—在
for
循环的每次迭代中创建一个新字典Label
。您只需创建一个包含所有defs
的字典相关问题 更多 >
编程相关推荐