拆分字符串 - Python
我想把一个字符串分割成这样:
["Date", "Start Time", "End Time", "Course Code", "Course Name", "Type", "Room", "Building", "Groups"]
我想分割的字符串大概长这样:
2024-03-21, 13:15 - 15:00 MVE545, Mathematical analysis, part 2, Lecture, Omega, 0, Jupiter, TIDAL-1, TIELL-1, , , , , ,
我最开始的想法是用", "来分割这个字符串,但这样会搞乱课程名称,因为课程名称里面也有", "。
另一个问题是,一个课程可能有多个课程代码。这样字符串就会变成这样:
2024-03-21, 13:15 - 15:00 MVE545, MVE545, Mathematical analysis, part 2, Lecture, Omega, 0, Jupiter, TIDAL-1, TIELL-1, , , , , ,
1 个回答
0
这听起来有点奇怪,但我用 split()
和列表切片的方法做了一个解决方案。
def parser(data):
return [data.split(',')[0]] + [[x.strip() for x in data.split(',')][1].split('-')[0].strip()] + [[y.strip() for y in [x.strip() for x in data.split(',')][1].split('-')][1].split(' ')[0]] + [[[y.strip() for y in [x.strip() for x in data.split(',')][1].split('-')][1].split(' ')[1]] + [x.strip() for x in data.split(',')][2:-14]] + [x.strip() for x in data.split(',')][-14:]
结果是:
['2024-03-21', '13:15', '15:00', ['MVE545'], 'Mathematical analysis', 'part 2', 'Lecture', 'Omega', '0', 'Jupiter', 'TIDAL-1', 'TIELL-1', '', '', '', '', '', '']
还有
['2024-03-21', '13:15', '15:00', ['MVE545', 'MVE545'], 'Mathematical analysis', 'part 2', 'Lecture', 'Omega', '0', 'Jupiter', 'TIDAL-1', 'TIELL-1', '', '', '', '', '', '']