2012-05-02 24 views
2

私は以下の問題のロジックに苦労しています。ロジックを釘付けにしても、私は不器用に実装するでしょうから、アドバイスはすばらしくなるでしょう。Python累積条件付きロジック

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

代わりに1メガファンクションでそれをやろうとする、より小さなステップにそれを打破します。

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') 
+0

うわー、私はヒープをあなたから答えました、ありがとう。 – MFB

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 
+0

私はあなたのポストからたくさんのことを学びましたが、私は1つの答えしかマークできません。どうもありがとう。 – MFB