python实现根据目标字符串修改一下行
需求:
根据source和dest两个文件,找出新增的命令行,然后在xml文件中根据命令修改id
输入souce:
ADD 100 SUB 200
输入dest:
MUL 300 DIV 400 ADD 100
输入macro:
<tar>MUL</tar> <id>0</id> ...... <tar>DIV</tar> <id>0</id>
输出:
<tar>MUL</tar> <id>300</id> ...... <tar>DIV</tar> <id>400</id>
实现代码:
#! /usr/bin/env python # encoding:utf-8 import re from bs4 import BeautifulSoup def chen(): file1 = 'D:\py\yeah\source.txt' file2 = 'D:\py\yeah\dest.txt' file3 = 'D:\py\yeah\macro.xml' source = [] dest = [] with open(file1, 'r') as f_s: for line in f_s: source.append(line.strip()) with open(file2, 'r') as f_d: for line in f_d: dest.append(line.strip()) result = [item for item in dest if item not in source] # 获取新增的命令 print(result) ''' f_xml = open(file3,'r+',encoding ='utf-8') soup = BeautifulSoup(f_xml,'xml') for item in soup.find_all('tar'): #找到tar的节点 next_sibling = item.find_next_sibling() #由于<tar></tar>和<id></id>是兄弟节点,可以通过查找下一个兄弟节点找到<MacroId> print(next_sibling.string) #修改<id></id>的内容 next_sibling.string = '0' ''' dic ={} for res in result: dic[re.sub('\d+','',res).strip()] = re.sub('\D+','',res).strip() data = [] with open(file3, 'r', encoding="utf-8") as f3_r: lines = f3_r.readlines() lineIdx = 0 while lineIdx < len(lines): if re.search('tar', lines[lineIdx]): # 查找到<CmdName> data.append(lines[lineIdx]) tarstr = re.findall(r"<tar>(.+?)</tar>",lines[lineIdx]) lineIdx += 1 # 索引到下一行 if tarstr[0] in dic.keys(): lines[lineIdx] = re.sub("\d+", dic[tarstr[0]], lines[lineIdx]) # 将ID替换为目标ID值 data.append(lines[lineIdx]) else: data.append(lines[lineIdx]) lineIdx += 1 with open(file3, 'w', encoding="utf-8") as f3_w: # 写回原文件 for item in data: f3_w.write(item) if __name__ == '__main__': chen()