2012-05-02 3 views
2

아래의 문제에 대한 논리로 고민 중입니다. 논리를 명시한 경우에도 실수로 구현할 것이므로 어떤 조언도 대단 할 것입니다.Python 누적 조건부 논리

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

I 필터의 목록을 가지고 있고이 경기를 결정하기 위해 파일 사전을 필터링 할 :

나는 파일을 나타내는 사전을 가지고있다. (작동하지 않는)이 작업을 수행하는 함수를 만드는에서

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

대신 하나의 메가 펑션에서 일을하려고의 작은 단계로 그것을 깰.

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

단순히 '기능'을 '기준'으로 사용할 수 있습니다. 이렇게하면 다른 사다리를 쓸 필요가 없으므로 훨씬 간단 해집니다. 이 같은 것 :

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

하나의 답변 만 표시 할 수 있지만 귀하의 게시물에서도 많은 것을 배웠습니다. 고마워. – MFB

관련 문제