[英]Search and replace between two files with search phrase in first file: Python
File 1: 文件1:
$def String_to_be_searched (String to be replaced with)
File 2: 档案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
I want to replace the "String to be searched" in file 2 with "String to be replaced with" from file 1 once each line of file 2 has the "String to be searched" in it. 一旦文件2的每一行都包含“要搜索的字符串”,我想用文件1中的“要替换的字符串”替换文件2中的“要搜索的字符串”。
My Code: 我的代码:
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()
Output So Far: 到目前为止的输出:
I have the Label as a Dictionary with the String to be searched and the string to be replaced. 我将Label作为字典,其中包含要搜索的字符串和要替换的字符串。 I am first trying to match the string in both files then I have to replace.
我首先尝试匹配两个文件中的字符串,然后必须替换。 But The second part does not give me any match... I used compare two file and find matching words in python this as a reference.
但是第二部分没有给我任何匹配...我使用比较两个文件并在python中找到匹配的单词作为参考。
For the "second part" - a regex isn't necessary to replace the text in File 2
. 对于“第二部分”,不需要用正则表达式替换
File 2
的文本。 Just read the entire file and use the str
method replace
. 只需读取整个文件,然后使用
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)
If you want to use the re
module, use re.sub
: 如果要使用
re
模块,请使用re.sub
:
for search_txt, replacement_txt in Label.iteritems():
data = re.sub(search_txt, replacement_txt, data)
print data
For the "first part" - you create a new dictionary, Label
, in every iteration of the for
loop. 对于“第一部分”-在
for
循环的每次迭代中创建一个新字典Label
。 You should just create one dictionary with all the defs
in it; 你应该创建一个字典,所有的
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.