import json
import re
#查找方式一
def find_all_indexes(sentence, sub_string):
return [i for i in range(len(sentence)) if sentence.startswith(sub_string, i)]
#查找方式二
def find_indices_with_regex(s, char):
return [m.start() for m in re.finditer("{}".format(char), s)]
#对应位置插入字符串
def insert_char_at_position(original_str, char_to_insert, position):
return original_str[:position] + char_to_insert + original_str[position:]
jsonstr = "{\"msg1\": \"s\", \"r\": \"A\", \"msg2\": \"b\"} {\"msg1\": \"g\", \"r\": \"R\", \"msg2\": \"e\"} {\"msg1\": \"i\", \"r\": \"V\", \"msg2\": \"d\"} {\"msg1\": \"b\", \"r\": \"E\", \"msg2\": \"n\"} "
jsonstr = jsonstr.replace("\\", "")
poslist = find_all_indexes(jsonstr, "}")
poslist.pop(-1)
for index, pos in enumerate(poslist):
jsonstr = insert_char_at_position(original_str=jsonstr, char_to_insert=",", position=pos + index + 1)
print(jsonstr)
print(poslist)
assistant_label = "[" + jsonstr + "]"
t_pred = json.loads(assistant_label)
print(len(t_pred))
python查找和插入子串位置并解析
于 2024-09-03 18:55:10 首次发布