正则表达式读取数据(七巧板)

之前的“七巧板”题使用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] == "<path":
            shape = [int(s) for s in line_tmp_split if s.isdigit()]  # <class 'list'>: [30, 20, 110, 20, 110, 120, 30, 120]
            shape_color = []  # <class 'list'>: ["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 = '<path([\d\D]*)/>'
    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也会跟着改变。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值