1

我有这段代码,我在其中搜索一个值(inputCategory),该值通常位于路径的末尾(例如/blah/blah/<category/blah,有时/blah/blah/<category>

def category_search(inputDirectory, inputCategory, root):
    categorySearch = os.path.split(os.path.normpath(inputDirectory)) 
    if categorySearch[1] == inputName:
        Logger.info("SEARCH: Files appear to be in their own directory")
        categorySearch2 = os.path.split(os.path.normpath(categorySearch[0]))
        if categorySearch2[1] == twoCategory or categorySearch2[1] == oneCategory:
            if not inputCategory:
            Logger.info("SEARCH: Determined Category to be: %s", categorySearch2[1])
                inputCategory = categorySearch2[1]
        elif not inputCategory:
            Logger.error("SEARCH: Could not identify category from the directory structure.")
            sys.exit(-1)
        else:
            pass

    elif categorySearch[1] == twoCategory or categorySearch[1] == oneCategory:
        if os.path.isdir(os.path.join(inputDirectory, inputName)):
            inputDirectory = os.path.join(inputDirectory, inputName)
        else:
            Logger.info("SEARCH: The directory passed is the root directory for category %s", categorySearch[1])
            Logger.info("SEARCH: We will try and determine which files to process, individually")
            root = 1
        if not inputCategory:
            Logger.info("SEARCH: Determined Category to be: %s", categorySearch[1])
            inputCategory = categorySearch[1]
    elif not inputCategory:
        Logger.error("SEARCH: Could not identify category from the directory structure")
        sys.exit(-1)
    else:
        Logger.info("SEARCH: The directory passed does not appear to include a category")
        root = 1
    return inputDirectory, inputCategory, root 

但问题是代码不是很动态,例如,如果我得到类似的路径/blah/blah/<category>/blah/blah

我正在寻找有关如何优化此代码、捕获上述情况以及可能更多的输入?

我是python的新手,所以要温柔:)谢谢你的帮助!

4

1 回答 1

0

我用这样的东西进行路径检查,但不确定它是否是你要找的……我在 python 中也很绿色!

# deconstruct the folder: /a/b/c --> /a/b --> /a --> /
pathHead, pathTail = os.path.split(inputDirectory)  
while pathTail and ( pathTail != inputCategory ): 
    pathHead,pathTail = os.path.split(pathHead)

if not pathTail:
    print 'didnt find category'
else:
    print 'found category: ',pathTail , ' in path: ' , pathHead

编辑:将 elif 固定为 else ...

于 2013-02-20T11:53:57.557 回答