三行实现模糊匹配
def fuzzyfinding(user_input,collection): s = [(len(re.compile('.*?'.join(user_input)).search(i).group()),re.compile('.*?'.join(user_input)).search(i).start(),i ) for i in collection if(re.compile('.*?'.join(user_input)).search(i))] return [x for _,_, x in sorted(s)]充分利用列表推导式;跟sql语句原理一样‘;
至于两行的太长了,你们去弄吧...import re
原文地址
10行python代码写的模糊查询
10行便于理解,结构严密; 如下:
>>> import re >>> def fuzzyfinder(user_input, collection): suggestions = [] pattern = '.*?'.join(user_input) # Converts 'djm' to 'd.*?j.*?m' regex = re.compile(pattern) # Compiles a regex. for item in collection: match = regex.search(item) # Checks if the current item matches the regex. if match: suggestions.append((len(match.group()), match.start(), item)) return [x for _, _, x in sorted(suggestions)]
本文地址:http://write.blog.csdn.net/postedit/52224806