0

我整天都在使用正则表达式将复杂的字符串解析为有意义的数据。我已经解决了几乎所有问题,但剩下最后一个问题:

我正在解析代表时间表的字符串列表。每天都是列表中的一个单独项目。有些日子一天有多个约会,比如这一行:

周二 10/13/2011 SHIFT 00:00-08:00 约会描述 DAYOFF 08:00-17:30 08:00-12:30 12:30-13:00 13:00-17:30 约会描述 NIGHT 17:30-24:00 预约说明

我希望这个字符串根据班次分成三行,但同时保持日期和日期。所有班次的共同点是它们由大写字母组成,因此 [AZ]。

预期输出为:

周二 10/13/2011 SHIFT 00:00-08:00 预约说明
周二 10/13/2011 DAYOFF 08:00-17:30 08:00-12:30 12:30-13:00 13:00-17 :30 描述
周二 10/13/2011 晚上 17:30-24:00 约会描述

我不能简单地扫描所有可能的转变,因为它们是未知的,唯一可以肯定的是它们都是大写的。因此我需要使用正则表达式。

我想到了这样的结构(regexmatch = a shift ([AZ]{5,})):

placeholder = []
for day in schedule:
    newLine = []
    if day.count(regexmatch) > 1:
        newline.append(day[:2])       #To include day and date
        i = 2
        for i < len(day):
            if day[i] == regexmatch:
                placeholder.append(newLine)
                newLine = []
                newLine.append(day[:2])
                newLine.append(day[i])
            else:
                newLine.append(day[i])
        i += 1
    placeholder.append(newLine)

我希望这是有道理的,有人可以帮助我实现正则表达式匹配,或者采取完全不同的路线。

4

1 回答 1

1

我会组织代码来生成约会(而不是重复附加到列表中):

import re
day_re = re.compile(r'((?:Mon|Tues|Wednes|Thurs|Fri|Sat|Sun)day \d{2}/\d{2}/\d{4}) (.*)')
shift_re = re.compile(r'([A-Z]{5,} [^A-Z]*(?:[A-Z]{1,4}[^A-Z]+)*)')

def appointments(lines):
    """
    Given iterator `lines` containing one or more appointments per day,
    generate individual appointments.
    """
    for line in lines:
        day, remainder = day_re.match(line).groups()
        shifts = shift_re.findall(remainder)
        if shifts:
            for shift in shifts:
                yield '{} {}'.format(day, shift.strip())
        else:
            yield '{} {}'.format(day, remainder.strip())
于 2012-12-06T13:23:47.843 回答