Python - поиск имени папки в пути к файлу - PullRequest
0 голосов
/ 27 апреля 2018

Мне нужно определить «episodeNumber» на основе имени папки в адресе файла. имя содержит 2 буквы «ep», за которыми следуют 3 цифры, от «001» до «999»

пример пути:

N://out/ep001/FX/maya/file4984.ma

Я ищу способ получить переменную, которая приведет к номеру эпизода (в этом примере ep001)

print(episodeNumber)
'ep001'

тогда я могу поместить "episodeNumber" в другой адрес, например

newPath = "Y://work/" + episodeNumber + "/comp/"
print(newPath)
'Y://work/ep001/comp/'

Как я могу определить номер эпизода в пути, чтобы поместить его в другой?

Я использую Python 2.7

спасибо

Ответы [ 2 ]

0 голосов
/ 28 апреля 2018

Я нахожу регулярное выражение мощным, но менее читабельным, особенно если вы давно его не использовали, поэтому вот решение без него с использованием других встроенных модулей.

import os
import fnmatch


def get_episode(path):
    # Split the path (should be OS independent).
    path_split = os.path.normpath(path).split(os.sep)

    # Find the episode using fnmatch.
    # This enforces your conventions that it must follow 3 numbers after 'ep'.
    episodes = fnmatch.filter(path_split, "ep[0-9][0-9][0-9]")
    if not episodes:
        raise RuntimeError, "Unable to detect episode in the supplied path."

    # In theory the path may yield multiple episodes from it, so just return the first one.
    return episodes[0]


episode = get_episode("N://out/ep001/FX/maya/file4984.ma")

# Use os.path.join to build your new path. 
new_path = os.path.join(os.path.normpath("Y://"), "work", episode, "comp")

Этот пример дает такой результат:

'ep001' # эпизод

'Y: \ work \ ep001 \ comp' # new_path (Я нахожусь на Windows, поэтому я получаю двойной обратная косая черта)

Лучше использовать os.path методы, чтобы он работал кроссплатформенно, чем + для построения ваших путей.

Это было проверено на Python 2.7.11

0 голосов
/ 27 апреля 2018
from __future__ import print_function
# the above import is for python2 compatibility (question author request)
# it has to be at the top of the module
# you may need to install it with `pip install future`

import re

file_address = 'N://sessionY/ep001/out-montageFX/maya/'

# ok let's write a regex to find the part we want
# here (ep) part means that we want to capture `ep` to a `capture group`
# the (\d{3}) part means match the exactly 3 integers and capture them
# [\\/] matches backward or forward slashes (for windows support)
# more on regexes here: https://docs.python.org/3/library/re.html#module-re
# on match objects here: 
# https://docs.python.org/3/library/re.html#match-objects

regex = r'[\\/](ep)(\d{3})[\\/]'

# next we apply the expression with re.search
# (which means find the first matching occurrence)
# details here: 
# https://docs.python.org/3/library/re.html#regular-expression-objects

m = re.search(regex, file_address, flags=re.IGNORECASE)

# the flags=re.IGNORECASE part - to match case-insensitivelly

if m:  # if a match has been found

    # we can get the folder_name `ep` part from the capture group 1
    # and the episode number from the capture group 2

    folder_name = m.group(1) + m.group(2)

    # as explained above the episode number is within group 1
    # and we also need to convert it to integer (if desired)
    # the group is guaranteed to have the match in it, because 
    # we are inside the above if statement.
    episode_number = int(m.group(2))

    # lets print the results:
    print('folder_name:', folder_name)
    print('episode_number:', episode_number)
else:
    # obviously no match
    print('no match')
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...