可以说我有一个清单
list = ['this','is','just','a','test']
如何让用户进行通配符搜索?
搜索词:“ th_s”
将返回“ this”
Answers:
**通配符吗?(e->我已经检查过文档-它不会以不同的方式对待斜杠,因此**此处甚至不需要通配符)。
fnmatch是“ Unix文件名模式匹配”。但是我只是尝试了一下,它似乎可以在Windows上运行。这是幸运的未定义行为,还是fnmatchWindows支持?
您是说通配符的任何特定语法吗?通常*代表“一个或多个”字符,并?代表一个。
最简单的方法可能是将通配符表达式转换为正则表达式,然后将其用于过滤结果。
fnmatch模块具有将通配符匹配转换为正则表达式的功能:fnmatch.translate
与Yuushi使用正则表达式的想法相同,但是它在re库中使用findall方法而不是列表理解:
import re
regex = re.compile('th.s')
l = ['this', 'is', 'just', 'a', 'test']
matches = re.findall(regex, string)
您为什么不只使用join功能?在正则表达式findall()或group()中,您将需要一个字符串,以便:
import re
regex = re.compile('th.s')
l = ['this', 'is', 'just', 'a', 'test']
matches = re.findall(regex, ' '.join(l)) #Syntax option 1
matches = regex.findall(' '.join(l)) #Syntax option 2
join()函数允许您转换字符串列表。连接之前的单引号是您将放在列表中每个字符串中间的内容。当您执行此代码部分(''.join(l))时,您会收到以下信息:
'这只是一个测试'
因此,您可以使用findal()函数。
我知道我迟到了7年,但是我最近创建了一个帐户,因为我正在学习,而其他人可能会有同样的问题。希望对您和其他人有帮助。
@FélixBrunet评论后更新:
import re
regex = re.compile(r'th.s')
l = ['this', 'is', 'just', 'a', 'test','th','s', 'this is']
matches2=[] #declare a list
for i in range(len(l)): #loop with the iterations = list l lenght. This avoid the first item commented by @Felix
if regex.findall(l[i]) != []: #if the position i is not an empty list do the next line. PS: remember regex.findall() command return a list.
if l[i]== ''.join(regex.findall(l[i])): # If the string of i position of l list = command findall() i position so it'll allow the program do the next line - this avoid the second item commented by @Félix
matches2.append(''.join(regex.findall(l[i]))) #adds in the list just the string in the matches2 list
print(matches2)