根据格式分离部分字符串

问题描述 投票:0回答:1

我想提供一个解决方案,根据格式链接分离任何字符串的一部分:

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"我只是想知道如何为此创建格式

python string format
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.