88

私がリストを持っているとしましょう

list = ['this','is','just','a','test']

ユーザーにワイルドカード検索を実行させるにはどうすればよいですか?

検索ワード:'th_s'

'this'を返します

4

7 に答える 7

178

使用fnmatch

import fnmatch
lst = ['this','is','just','a','test']
filtered = fnmatch.filter(lst, 'th?s')

_ワイルドカードとして許可する場合は、すべての下線を(1文字の場合)または(複数文字の場合)に置き換えます。'?'*

ユーザーがさらに強力なフィルタリングオプションを使用できるようにする場合は、正規表現の使用をユーザーに許可することを検討してください。

于 2012-07-11T06:57:55.047 に答える
58

正規表現は、おそらくこの問題の最も簡単な解決策です。

import re
regex = re.compile('th.s')
l = ['this', 'is', 'just', 'a', 'test']
matches = [string for string in l if re.match(regex, string)]
于 2012-07-11T07:00:59.837 に答える
8

fnmatchモジュールを試すことができます。これには、シェルのようなワイルドカード構文があります。

または正規表現を使用できます

再インポート

于 2012-07-11T07:04:42.460 に答える
1

ワイルドカードの特定の構文を意味しますか?通常*、「1つまたは複数の」文字を?表し、1つを表します。

最も簡単な方法は、ワイルドカード式を正規表現に変換し、それを使用して結果をフィルタリングすることです。

于 2012-07-11T06:57:36.150 に答える
0

正規表現を使用するという点でYuushiと同じ考えですが、これはリスト内包表記の代わりにreライブラリ内のfindallメソッドを使用します。

import re
regex = re.compile('th.s')
l = ['this', 'is', 'just', 'a', 'test']
matches = re.findall(regex, string)
于 2017-07-20T13:47:35.667 に答える
0

結合機能だけを使ってみませんか?正規表現の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)
于 2019-10-17T17:41:56.473 に答える
-8

簡単な方法は試してみてくださいos.system

import os
text = 'this is text'
os.system("echo %s | grep 't*'" % text)
于 2017-09-07T05:33:11.500 に答える