布尔检查字典

时间:2017-05-11 18:58:10

标签: python parsing dictionary boolean directory

我有解析和查找特定文件夹的功能(如果存在)。

目标:如果字典中存在这些文件夹,我想以绿色(文件夹存在)或红色(文件夹不存在)打印它们。我在字典上进行布尔检查时遇到问题。我对python很新。

def parse_directory(startpath):
for dir_path, folders, filenames in os.walk(startpath):
    path_level = dir_path.replace(startpath, '').count(os.sep) 
    relative_dir = dir_path.replace(startpath, '').strip(os.sep)
    current_dir = dir_path.split(os.sep)[-1]


    if path_level == 1:
        mnemonic = relative_dir
        client_dictionary[mnemonic] = {}


        if "4x Clinic" in folders:
            client_dictionary[mnemonic]["clinic"] = True
        else: 
            client_dictionary[mnemonic]["clinic"] = False

        if "4x Hospital" in folders:
            client_dictionary[mnemonic]["hospital"] = True
        else: 
            client_dictionary[mnemonic]["hospital"] = False

        if "4x Lab" in folders:
            client_dictionary[mnemonic]["lab"] = True
        else:
            client_dictionary[mnemonic]["lab"] = False

        if "Hub Millennium" in folders:
            client_dictionary[mnemonic]["hub_millennium"] = True
        else:
            client_dictionary[mnemonic]["hub_millennium"] = False

        if "Client Millennium" in folders:
            client_dictionary[mnemonic]["client_millennium"] = True 
        else:
            client_dictionary[mnemonic]["client_millennium"] = False

上面的代码解析。现在进行布尔检查我有2个函数,1到get_status,另一个print_colored_mnemonics打印mneonics(绿色,如果存在)红色(不存在)。

以下是get_status代码:

def get_status(startpath):
for dict_keys, dict_values in parsing_dict.items():
    if all(dict_values):
        return True
    elif any(dict_values):
        return False

以下是print_colored_mnemonics代码:

def print_colored_mnemonics(startpath):

RED = "\033[91m"
RED2 = "\033[0m"
GREEN = "\033[92m"
GREEN2 = "\033[0m"

if get_status(startpath) == True:
    print(GREEN + '{}'.format(dict_keys) + GREEN2)
    if get_status(startpath) == False:
        print(RED + '{}'.format(dict_keys) + RED2)

我这样做了吗?如果存在任何内容,我基本上希望字典的键(助记符)是绿色的。如果Key没有任何内容,那么助记符应该用红色打印。

1 个答案:

答案 0 :(得分:2)

我在工作空间中创建了一个名为medical的目录。然后我创建了这样的子目录:

medical/
    remember/
        4x Clinic
        Hub Millenium

然后我拿了你的代码并制作了这个脚本:

#!python3
import sys
import os

client_dictionary = {}

def parse_directory(startpath):
    print("startpath:", startpath)
    for dir_path, folders, filenames in os.walk(startpath):
        path_level = dir_path.replace(startpath, '').count(os.sep)
        relative_dir = dir_path.replace(startpath, '').strip(os.sep)
        current_dir = dir_path.split(os.sep)[-1]

        if path_level == 1:
            mnemonic = relative_dir
            client_dictionary[mnemonic] = {}

            if "4x Clinic" in folders:
                client_dictionary[mnemonic]["clinic"] = True
            else:
                client_dictionary[mnemonic]["clinic"] = False

            if "4x Hospital" in folders:
                client_dictionary[mnemonic]["hospital"] = True
            else:
                client_dictionary[mnemonic]["hospital"] = False

            if "4x Lab" in folders:
                client_dictionary[mnemonic]["lab"] = True
            else:
                client_dictionary[mnemonic]["lab"] = False

            if "Hub Millennium" in folders:
                client_dictionary[mnemonic]["hub_millennium"] = True
            else:
                client_dictionary[mnemonic]["hub_millennium"] = False

            if "Client Millennium" in folders:
                client_dictionary[mnemonic]["client_millennium"] = True
            else:
                client_dictionary[mnemonic]["client_millennium"] = False


root_dir = '.' if len(sys.argv) < 2 else sys.argv[1]
parse_directory(root_dir)
print(client_dictionary)

输出是这样的:

$ python test.py medical
startpath: medical
{'remember': {'hub_millennium': False, 'lab': False, 'client_millennium': False, 'hospital': False, 'clinic': True}}

其中remembermnemonic,无论是什么,其他内容似乎都符合您的代码所期望的内容。

在我做任何其他事情之前,我将收紧parse_directory功能。正如@kindall指出的那样,可以使用更短的形式。我也要mv Hub\ Millenium Hub\ Millennium - 我的拼写错误!

#!python3
import sys
import os

# If a mnemonic folder contains KEY, then it has features VALUE
FEATURES = {
    '4x Clinic' : 'clinic',
    '5x Clinic' : 'clinic', # Supports multiple values!
    '4x Hospital' : 'hospital',
    '4x Lab' : 'lab',
    'Hub Millennium' : 'hub_millennium',
    'Client Millennium': 'client_millennium',
}

def parse_directory(startpath):
    print("startpath:", startpath)

    client_dictionary = {}

    for dir_path, folders, filenames in os.walk(startpath):
        path_level = dir_path.replace(startpath, '').count(os.sep)
        relative_dir = dir_path.replace(startpath, '').strip(os.sep)
        current_dir = dir_path.split(os.sep)[-1]

        if path_level == 1:
            mnemonic = relative_dir

            # Set all features to False
            cdm = {v:False for k,v in FEATURES.items()}

            for folder,feature in FEATURES.items():
                if folder in folders:
                    cdm[feature] = True

            client_dictionary[mnemonic] = cdm

    return client_dictionary

root_dir = '.' if len(sys.argv) < 2 else sys.argv[1]
client = parse_directory(root_dir)
print(client)

这会产生相同的输出:

$ python test.py medical
startpath: medical
{'remember': {'clinic': True, 'client_millennium': False, 'lab': False, 'hub_millennium': True, 'hospital': False}}

接下来,我添加了一个新的子目录medical/allfeatures,并创建了所有各种子目录:4x Lab,4x Clinic等。

然后我添加了这段代码:

def get_status(mnemonic):
    """Return True if all values of mnemonic dict are true, else False"""
    return False not in mnemonic.values()

root_dir = '.' if len(sys.argv) < 2 else sys.argv[1]
client = parse_directory(root_dir)
print("Client Info:", client)
for mnemonic in client:
    print("Status of {}: {}".format(mnemonic, get_status(client[mnemonic])))

输出现在看起来像这样:

$ python test.py medical
startpath: medical
Client Info: {'allfeatures': {'clinic': True, 'hub_millennium': True, 'hospital': True, 'lab': True, 'client_millennium': True}, 'remember': {'clinic': True, 'hub_millennium': True, 'hospital': False, 'lab': False, 'client_millennium': False}}
Status of allfeatures: True
Status of remember: False

我认为这就是你要做的。如果是这样,您可以使用以下内容打印颜色:

if get_status(client[mnemonic]):
    color_start = GREEN
    color_end = GREEN2
else:
    color_start = RED
    color_end = RED2

print(color_start, mnemonic, color_end)