之前的“七巧板”题使用split()读取.xml文件中的数据,现在改用正则表达式读取
代码:
import re
import copy
# get colours and coordinates
def available_coloured_pieces_orig(file_name):
# get all coordinates from file
coloured_pieces = [] # store coordinates
line = file_name.readline()
while line:
line_tmp = copy.deepcopy(line) # deepcopy for using split() function
line_tmp_split = line_tmp.split()
if len(line_tmp_split) > 0 and line_tmp_split[0] == ": [30, 20, 110, 20, 110, 120, 30, 120]
shape_color = [] # : ["red", (30, 20), (110, 20), (110, 120), (30, 120)]
shape_color.append(line_tmp.split('"')[-2])
for i in range(len(shape))[::2]:
point = (shape[i], shape[i+1])
shape_color.append(point)
coloured_pieces.append(shape_color) # store each shape's coordinates
line = file_name.readline()
return coloured_pieces
# regular_expression
def available_coloured_pieces(file_name):
coloured_pieces = [] # store coordinates
# shape_color = []
line = file_name.readline()
info_pattern = ' '
point_pattern = ' (\d+)'
color_pattern = '"(\w+)"'
while line:
line_info = re.findall(info_pattern, line)
if line_info:
line_point = re.findall(point_pattern, line_info[0])
line_color = re.findall(color_pattern, line_info[0])
shape_color = []
# shape_color.clear()
shape_color.append(line_color[0])
for i in range(len(line_point))[::2]:
point = (int(line_point[i]), int(line_point[i + 1]))
shape_color.append(point)
coloured_pieces.append(shape_color)
line = file_name.readline()
return coloured_pieces
file = open('tangram_A_1_a.xml')
coloured_pieces_orig = available_coloured_pieces_orig(file)
file = open('tangram_A_1_a.xml')
coloured_pieces = available_coloured_pieces(file)
print(coloured_pieces == coloured_pieces_orig)
注:文中若使用初始定义的shape_color=[],并使用shape_color.clear()和coloured_pieces.append(shape_color)会出错,因为append进去的是索引值,因此之后改变shape_color的内容,coloured_pieces中之前append进去的shape_color也会跟着改变。