我在HTML代码中有这个:
"name":"London Street" dsakjhasfsa safksafas "north":"232","south":"12","east":"113","west":"9","curRoom":"110"
"name":"London Street" something asdgas dsakhdask "north":"0","south":"22","east":"131","west":"19","curRoom":"10"
我试过那些有正则表达式的人,但不知怎的,我在某处失败了。
\"name\":\"\A(...)\Z\"*?north\":\"(d+)\",\"south\":\"(\d+)\",east\":\"(\d+)\",west\":\"(\d+)\",curRoom\":\"(\d+)\"
\"name\":\"^(...)$\"*?north\":\"(\d+)\",\"south\":\"(\d+)\",east\":\"(\d+)\",west\":\"(\d+)\",currentRoom\":\"(d+)\"
\"name\":\"(...)+\"*?north\":\"(\d+)\",\"south\":\"(d+)\",east\":\"(d+)\",west\":\"(\d+)\",currentRoom\":\"(\d+)\"
有了这些捕获,我想创建一个这样的字典: {key是当前房间,值[位置0:带有邻居的列表[1,2,3],位置1 - 房间的名称]}
我只知道如何实现这一目标,通过为每个房间的变量分配变量,如下所示:
list_of_neighbours = []
number_south = re.findall('south\":\"(\d+)\"', url)
list_of_neighbours.append(number_south)
....
list_of_neighbours = [n,s,e,w]
dictionay ={}
for k, v in list_of_neighbours:
dictionay[k] = str(number_current_room)
dictionay[k].append(v)
但这不会增加空间并且步骤太多。 问题是:它可能是一个较短的版本?以及如何修复正则表达式?谢谢
答案 0 :(得分:3)
您正尝试使用正则表达式解析JSON。别。 JSON基本上已经一个字典,只是以标准格式字符串化。
使用json
模块:
import json
rooms = json.loads(some_json_string)