python-给定格式和字符串,从该字符串获取信息

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

我想在datetime模块中执行类似于strptime方法的操作。给定格式和字符串,请更改该字符串的格式并返回新字符串。因此,例如,我有一个电视剧集的文件名,我调用此函数来更改文件名的格式,指定标题在哪里,该集在哪里,质量等等。

def change_format(file_name, format, season=1):
    title = # Get the title applying the format to the string
    episode = # Get the episode applying the format to the string
    season = # Get the season applying the format to the string or from the variable in the function
    quality # Get the quality applying the format to the string
    return f'{title} + S{season}E{episode} [{quality}]'

可能会或可能不会提供某些信息(例如,如果未提供质量,则不要在退货中使用它,并且可能会有其他信息。

change_format('Some Title Here - 1 [1080p] [CDI3989AFM]', '%t - %e [%q][%i]')

[这里,%t是标题,%e是情节,%q是质量,%i是一些额外信息。标题为3个字,因此也许您应该指定字数?

预期输出:

"Some Title Here S01E01 [1080p] [CDI3989AFM]"
python regex format
1个回答
0
投票

您可以为此使用正则表达式:

import re

r = re.match('(.*).*(\[.*\]).*(\[.*\])', 'Some Title Here - 1 [1080p] [CDI3989AFM]')
r.group(1) # Some Title Here - 1 
r.group(2) # [1080p] 
r.group(2) # [CDI3989AFM]
© www.soinside.com 2019 - 2024. All rights reserved.