LEATH
使用正则表达式import rehtml = '''{ "id" : 10, "name" : "bob", "data" : "<some> \n <xml> \n <in here>"},{ "id" : 20, "name" : "jane", "data" : "<other> \n <xml> \n <in here>"}'''def replaceReg(html, regex, new): return re.sub(re.compile(regex), new, html)html = replaceReg(html,' \n ',' ')html = replaceReg(html,'{[\s]+','{ ')html = replaceReg(html,'[\s]+}',' }')html = replaceReg(html,',[\s]+',', ')html = replaceReg(html,'}, ','\n')print (html)结果:{ "id" : 10, "name" : "bob", "data" : "<some> <xml> <in here>" { "id" : 20, "name" : "jane", "data" : "<other> <xml> <in here>" }
HUH函数
您只需要在写入另一个文件时替换结束换行符(\n ):s=''with open('input.txt','r') as f_in, open('output.txt', 'w') as f_out: for line in f_in: s += line.replace('\n', '') f_out.write(s)其中 input.txt 具有以下数据:{ "id" : 10, "name" : "bob", "data" : "<some> \n <xml> \n <in here>"},{ "id" : 20, "name" : "jane", "data" : "<other> \n <xml> \n <in here>"}