我有以下格式的输入文件:
<ftnt>
<p><su>1</su> aaaaaaaaaaa </p>
</ftnt>
...........
...........
...........
... the <su>1</su> is availabe in the .........
我需要通过替换值并删除ftnt
标记中的全部数据,将其转换为以下格式:
请找出我写的代码。最初,我将键和值保存在字典中,并尝试使用分组替换基于键的值。在
import re
dict = {}
in_file = open("in.txt", "r")
outfile = open("out.txt", "w")
File1 = in_file.read()
infile1 = File1.replace("\n", " ")
for mo in re.finditer(r'<p><su>(\d+)</su>(.*?)</p>',infile1):
dict[mo.group(1)] = mo.group(2)
subval = re.sub(r'<p><su>(\d+)</su>(.*?)</p>','',infile1)
subval = re.sub('<su>(\d+)</su>',dict[\\1], subval)
outfile.write(subval)
我试图在re.sub
中使用字典,但是我得到了一个KeyError
。我不知道为什么会这样,你能告诉我怎么用吗。我很感激你的帮助。在
首先,不要命名字典
dict
,否则会破坏dict
函数。其次,\\1
不能在字符串之外工作,因此出现语法错误。我认为最好的办法是利用str.format相关问题 更多 >
编程相关推荐