python文件操作

import sys
from matchKey import *

def readKeyconf(filename):
    try:
        keystream = open(filename)
    except Exception:
        return None
    keyconf = {}
    atts = {}
    key = None
    for line in keystream:
        line = line.strip()
        if len(line) <= 0:
            continue

        if line.startswith('#'):
            key = line.split()[1]
            atts = {}
        else:
            '''
            {'KEY_ALA':{'/search/index':{'match':'^ala.*'}}}
            '''
            confs = line.split(' ',1)
            if len(confs) <= 1:
                atts[confs[0]] = ''
            else:
                atts[confs[0]] = confs[1]
            keyconf[key] = atts
        #print(line)
    return keyconf


if __name__ == '__main__':
    t = {'urlpath':'/search/wiseala','tn':'wiseala','dulisearch':'1'}
    keyconf = readKeyconf('keyconf.txt')
    if keyconf is None:
        print('None')
    else:
        print(keyconf)
    for key in keyconf:
        if matchKey(keyconf,key,t):
            print(key)
 
 
 
 
import sys
import re
def isMatchAttribute(cl,cmd,value,atts):
    ok = False
    if cl not in atts:
        return ok
    if cmd == '=':
        if atts[cl] == value:
            ok = True
    elif cmd == 'match':
        pat = re.compile(value)
        if pat.match(atts[cl]):
            ok = True
    return ok

def matchKey(keyconf,keyname,atts):
    pat = keyconf[keyname]
    # 匹配所有的属性才算匹配成功
    ok = True
    for cl in pat:
        vals = pat[cl].split()
        if len(vals) <= 1:
            cmd = vals[0]
            value = ""
        else:
            cmd = vals[0]
            value = vals[1]
        if not isMatchAttribute(cl,cmd,value,atts):
            ok = False
            break
    return ok
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值