根据格式分隔字符串的一部分

时间:2019-03-04 15:05:30

标签: python string format

我想提供一个基于以下格式链接来分隔任何字符串部分的解决方案:

Drop the Mic S02E16 1080p WEB x264-TBS ====> Drop the Mic S02E16


Hughesy We Have A Problem S03E05 720p HDTV x264-CBFM ======> Hughesy We Have A Problem S03E05


Dead of Winter S01E03 Winters Bone 1080p WEB x264-UNDERBELLY ======> Dead of Winter S01E03


Saturday Night Live S44E14 John Mulaney 720p WEB x264-TBS =====>  Saturday Night Live S44E14

传入的字符串不是猜测值,但是所有主题的格式都如下:"some text some text " + "S00E00" + "some text some text"我只是想了解如何为此创建格式

1 个答案:

答案 0 :(得分:1)

正则表达式在这里似乎很合适-搜索“ S”,后跟一些数字,然后是“ E”,再跟一些数字。

import re

def get_title(s):
    m = re.match(".*S\d+E\d+", s)
    if not m: raise Exception("Couldn't find S<num>E<num> substring")
    return m.group(0)

test_cases = [
    "Drop the Mic S02E16 1080p WEB x264-TBS",
    "Hughesy We Have A Problem S03E05 720p HDTV x264-CBFM",
    "Dead of Winter S01E03 Winters Bone 1080p WEB x264-UNDERBELLY",
    "Saturday Night Live S44E14 John Mulaney 720p WEB x264-TBS"
]

for s in test_cases:
    print(s, "====>", get_title(s))

结果:

Drop the Mic S02E16 1080p WEB x264-TBS ====> Drop the Mic S02E16
Hughesy We Have A Problem S03E05 720p HDTV x264-CBFM ====> Hughesy We Have A Problem S03E05
Dead of Winter S01E03 Winters Bone 1080p WEB x264-UNDERBELLY ====> Dead of Winter S01E03
Saturday Night Live S44E14 John Mulaney 720p WEB x264-TBS ====> Saturday Night Live S44E14

如果需要分别访问标题的每个部分,则可以使用捕获组:

import re

def get_info(s):
    m = re.match("(.*)(S\d+E\d+)(.*)", s)
    if not m: raise Exception("Couldn't find S<num>E<num> substring")
    return m.groups()

test_cases = [
    "Drop the Mic S02E16 1080p WEB x264-TBS",
    "Hughesy We Have A Problem S03E05 720p HDTV x264-CBFM",
    "Dead of Winter S01E03 Winters Bone 1080p WEB x264-UNDERBELLY",
    "Saturday Night Live S44E14 John Mulaney 720p WEB x264-TBS"
]

for s in test_cases:
    title, episode_num, format_info = get_info(s)
    print(s)
    print("\tTitle:", title)
    print("\tEpisode Number:", episode_num)
    print("\tFormat Info:", format_info)

结果:

Drop the Mic S02E16 1080p WEB x264-TBS
        Title: Drop the Mic
        Episode Number: S02E16
        Format Info:  1080p WEB x264-TBS
Hughesy We Have A Problem S03E05 720p HDTV x264-CBFM
        Title: Hughesy We Have A Problem
        Episode Number: S03E05
        Format Info:  720p HDTV x264-CBFM
Dead of Winter S01E03 Winters Bone 1080p WEB x264-UNDERBELLY
        Title: Dead of Winter
        Episode Number: S01E03
        Format Info:  Winters Bone 1080p WEB x264-UNDERBELLY
Saturday Night Live S44E14 John Mulaney 720p WEB x264-TBS
        Title: Saturday Night Live
        Episode Number: S44E14
        Format Info:  John Mulaney 720p WEB x264-TBS