[英]Split one file into multiple files based on pattern (cut can occur within lines)
[英]Split one line to multiple lines based on pattern
我整天都在使用正則表達式,將復雜的字符串解析為有意義的數據。 我釘了幾乎所有東西,但剩下最后一個問題:
我正在解析代表時間表的字符串列表。 每天是列表中的單獨項目。 某些天一天有多個約會,例如以下行:
2011年10月13日星期二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]。
預期輸出為:
2011年10月13日,星期二,SHIFT 00:00-08:00任命說明
2011年10月13日星期二DAYOFF 08:00-17:30 08:00-12:30 12:30-13:00 13:00-17:30說明
2011年10月13日星期二晚上17:30-24:00約會描述
我不能簡單地掃描所有可能的班次,因為它們是未知的,唯一可以肯定的是它們全部都處於上限。 因此,我需要使用正則表達式。
我想到了這樣的結構(regexmatch =移位([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)
我希望這是有道理的,並且有人可以幫助我在其中實現regexmatch,或者采取完全不同的方法。
我整理了代碼以生成約會(而不是重復追加到列表中):
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())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.