【发布时间】:2014-11-28 03:41:10
【问题描述】:
文件 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 的每一行都包含“要搜索的字符串”,我想将文件 2 中的“要搜索的字符串”替换为文件 1 中的“要替换的字符串”。
我的代码:
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这个作为参考。
【问题讨论】:
-
${String to be searched}是多个词还是一个词,因为您的正则表达式目前限制为${foo} -
所以它主要是一个词。喜欢:Foo 或 Foo_Bar ...
-
你应该循环:
for x in matches: print x -
好的,打印出匹配项。现在我如何只替换第一行中的那个字符串? line = line.replace(match, labelValues) 会起作用吗?
-
除了被替换的字符串之外,您希望 file2 完全相同吗?