2

我正在为以下问题的逻辑而苦苦挣扎,我知道即使我确定了逻辑,我也可能会笨拙地实现它,所以任何建议都会很棒。

我有一个代表文件的字典:

the_file = {'Filename':'x:\\myfile.doc','Modified':datetime(2012,2,3),'Size':32412}

我有一个过滤器列表,我想过滤文件字典以确定匹配项。

filters = [
    {'Key':'Filename','Criteria':'Contains','Value':'my'},
    {'Key':'Filename','Criteria':'Does not end with','Value':'-M.txt'},
    {'Key':'Modified','Criteria':'After','Value':datetime(2012,1,1)}
    ]

我最好的尝试创建一个函数来做到这一点(这不起作用):

def is_asset(the_file, filters):
match = False
for f in filters:
    if f['Key'] == u'Filename':
        if f['Criteria'] == u'Contains':
            if f['Value'] in the_file['Filename']:
                match = True
        elif f['Criteria'] == u'Starts with':
            if the_file['Filename'].startswith(f['Value']):
                match = True
        elif f['Criteria'] == u'Ends with':
            if the_file['Filename'].endswith(f['Value']):
                match = True
        elif not f['Criteria'] == u'Does not end with':
            if the_file['Filename'].endswith(f['Value']):
                match = False
        elif f['Criteria'] == u'Equals':
            if os.path.basename(the_file['Filename']) == f['Value']:
                match = True
        elif f['Criteria'] == u'Does not contain':
            if f['Value'] in the_file['Filename']:
                match = False
    elif f['Key'] == u'Modified':
        mtime = int(os.path.getmtime(the_file['Filename']))
        if f['Criteria'] == u'Before':
            if f['Value'] > datetime.fromtimestamp(mtime):
                the_file['Modified'] = mtime
                match = True
        elif f['Criteria'] == u'After':
            if f['Value'] < datetime.fromtimestamp(mtime):
                the_file['Modified'] = mtime
                match = True
    elif f['Key'] == u'Size':
        size = long(os.path.getsize(the_file['Filename']))
        if f['Criteria'] == u'Bigger':
            if f['Value'] < size:
                the_file['Size'] = size
                match = True
            elif f['Value'] > size:
                the_file['Size'] = size
                match = True
    if match:
        return the_file
4

2 回答 2

4

与其尝试在一个宏功能中完成,不如将其分解为更小的步骤。

filenamecondmap = {
  u'Contains': operator.contains,
  u'Does not end with': lambda x, y: not x.endswith(y),
   ...
}

 ...

condmap = {
  u'Filename': filenamecondmap,
  u'Modified': modifiedcondmap,
   ...
}

然后遍历结构直到你有条件,然后执行它。

condmap[u'Filename'][u'Contains'](thefile['Filename'], 'my')
于 2012-05-02T04:23:56.673 回答
2

您可以简单地使用函数作为您的“标准”。这使它变得更加简单,因为您不必编写大的 if-else 阶梯。像这样的东西:

def contains(value, sub):
    return sub in value

def after(value, dt):
    return value > dt

filters = [
    {'Key': 'FileName', 'Criteria': contains, 'Value': 'my'},
    {'Key': 'Modified', 'Criteria': after,  'Value': datetime(2012,1,1)}
]

for f in filters:
    if f['Criteria'](filename[f['Key']], f['Value']):
       return True
于 2012-05-02T04:34:35.510 回答