本文主要是介绍python json编码及字符串的处理(间隔n个字符插入一个换行符),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
使用Python处理json文件时,经常会遇到一些编码的问题。本次分享一下,python加载json文件,编码以及序列化。
1.需求:给定一个字符串,对字符串遍历,每隔16个字符插入一个换行符,具体实现代码如下:
import json
import re
import sys
import os
s="愿你合上笔盖的刹那,有着侠客收剑入鞘的骄傲"
s=re.sub(r"(.{16})","\\1\n",s)
print(s)
2.加载json文件并将其序列化为对象,并更改对象的question属性,重新写入新的json对象
import json
import re
import sys
import osfile=open("temp.json","r",encoding='utf-8')
info=json.load(file)
listArray=info["listArray"]
it=iter(listArray)
for x in it:s=x["question"]s=re.sub(r"(.{16})","\\1\n",s)x["question"]=s
tempArray=listArray
fp=open("answer.json",'w+',encoding='utf-8')
fp.write(json.dumps(tempArray,ensure_ascii=False))
3.temp.json 文件如下:
{"listArray":[{"ID": 1,"question": "请问“匈奴不灭,何以为家”表达了哪位将军的爱国情怀?","A": "卫青","B": "霍去病","C": "李广","correct": "B"},{"ID": 2,"question": "请问诗句“朔方烽火照甘泉,长安飞将出祁连。”中的“飞将”指的是?","A": "卫青","B": "李广","C": "马援","correct": "B"},{"ID": 3,"question": "请问诗句“出身仕汉羽林郎,初随骠骑战渔阳。”中的“骠骑”是指?","A": "霍去病","B": "卫青","C": "李广","correct": "A"},{"ID": 4,"question": "请问诗句“伏波惟愿裹尸还”中“伏波”是指?","A": "傅介子","B": "马援","C": "班超","correct": "B"}]
}
4.输出的json文件如下所示:
[{"ID": 1,"question": "请问“匈奴不灭,何以为家”表达了\n哪位将军的爱国情怀?","A": "卫青","B": "霍去病","C": "李广","correct": "B"},{"ID": 2,"question": "请问诗句“朔方烽火照甘泉,长安飞\n将出祁连。”中的“飞将”指的是?\n","A": "卫青","B": "李广","C": "马援","correct": "B"},{"ID": 3,"question": "请问诗句“出身仕汉羽林郎,初随骠\n骑战渔阳。”中的“骠骑”是指?","A": "霍去病","B": "卫青","C": "李广","correct": "A"},{"ID": 4,"question": "请问诗句“伏波惟愿裹尸还”中“伏\n波”是指?","A": "傅介子","B": "马援","C": "班超","correct": "B"}
]
更多内容欢迎关注公众号:
这篇关于python json编码及字符串的处理(间隔n个字符插入一个换行符)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!