【发布时间】:2017-07-02 15:08:33
【问题描述】:
我有一个包含数据类别名称的 Python 2.7 集合对象,我希望能够进行某种形式的模糊元素检查,以查看用户给定输入的一部分是否是集合的元素。
这是一个玩具示例,用于解释我想要什么。给定以下集合和用户输入:
SET = {'red_ball', 'green_ball', 'red_cup', 'green_cup'}
user_input = 'yellow ball'
我希望程序打印出如下内容:
'yellow_ball' not found, did you mean 'red_ball', or 'green_ball'?
到目前为止,我有以下内容:
import re
SET = {'red_ball', 'green_ball', 'red_cup', 'green_cup'}
user_input = 'yellow ball'
# all members of my set are lowercase and separated by an underscore
user_input_list = user_input.lower().split() # for use in fuzzy search
user_input = "_".join(user_input_list) # convert to yellow_ball for element check
regex = None
matches = []
if user_input not in SET:
# FUZZY ELEMENT CHECK
for item in user_input_list:
regex = re.compile(item)
for element in SET:
if regex.match(element):
matches.append(element)
if len(matches) > 0:
print '\'%s\' not found, did you mean %s' % (user_input, ", ".join(['\'' + x + '\'' for x in matches]))
else:
print '\'%s\' not found.' % user_input
有没有更有效的方法来做到这一点,也许是使用第三方库?
感谢您的帮助, 杰兰特
【问题讨论】:
-
你为什么使用正则表达式?只需使用
item in element,它会做同样的事情。 -
你的解决方案有效吗?
-
@Artyer 感谢您的推荐,我已经更改了它,它仍然可以按预期工作。
-
@GeraintBallinger 你对第 3 方库感兴趣吗?
-
@cᴏʟᴅsᴘᴇᴇᴅ 是的,我将编辑我的问题以进行澄清
标签: python python-2.7 set fuzzy-search