使用第一个文件中的搜索短语在两个文件之间搜索和替换:Python
文件1:使用第一个文件中的搜索短语在两个文件之间搜索和替换:Python,python,regex,string,match,Python,Regex,String,Match,文件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 f
$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()
迄今为止的产出:
我将标签作为字典,其中包含要搜索的字符串和要替换的字符串。我首先尝试匹配两个文件中的字符串,然后必须替换。但是第二部分没有给我任何匹配。。。我用这个作为参考 对于第二部分-不需要正则表达式来替换文件2中的文本。只需读取整个文件并使用str方法replace 如果要使用re模块,请使用re.sub: 对于第一部分,在For循环的每个迭代中创建一个新的字典Label。你应该创建一个包含所有def的字典
是${String to search}多个单词还是一个单词,因为您的正则表达式当前限制为类似${foo}的内容,所以它主要是一个单词。例如:Foo或Foo_Bar…并且您应该在匹配中循环:for x:print xOkay以打印匹配。现在我如何替换第一行中的字符串?line=line.replacematch,LabelValue是否有效?是否希望文件2除了替换的字符串之外完全相同?当我尝试在for循环中打印searchtxt和替换txt时,它不会打印出来。。是否可以像您所做的那样调用Label.iteritems???@Doodle是的,请参见教程中的内容。创建一个dict帮助的标签!!谢谢。
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)
for search_txt, replacement_txt in Label.iteritems():
data = re.sub(search_txt, replacement_txt, data)
print data
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