2017-07-02 8 views
0

データカテゴリの名前を含むPython 2.7セットオブジェクトがあります。入力を与えられたユーザーの一部が要素であるかどうかを確認するために、何らかのファジー要素チェックを実行したいと考えています。セット。Pythonファジー要素のチェック

私は何をしたいのかを説明するおもちゃの例です。これまでのところ、私は以下のいる

'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 

は、私はプログラムは、次のようなものをプリントアウトしたい

SET = {'red_ball', 'green_ball', 'red_cup', 'green_cup'} 
user_input = 'yellow ball' 

次のセットと、ユーザーの入力を考えますおそらく第三者のライブラリを使用する、これを行うより効率的な方法がありますか?あなたの助けのための

おかげで、 ゲラント

+2

なぜ正規表現を使用していますか? 'item in element'を使うだけで、同じことができます。 – Artyer

+0

あなたのソリューションは機能しますか? – wwii

+0

@Artyerあなたの推薦に感謝、私はそれを変更し、それはまだ期待どおりに動作します。 –

答えて

2

あなたは、サードパーティのモジュールに興味があるなら、私はPythonでファジー文字列マッチングのために、fuzzywuzzyと呼ばれるこの種のもののために使用したい素敵な小さなモジュールがあります。

このモジュールは、わずか2行のコードでファジー文字列のマッチングを実行します。

は、ここであなたがそれを使用する方法の例です:

>>> from fuzzywuzzy import process 
>>> choices = {'red_ball', 'green_ball', 'red_cup', 'green_cup'} 
>>> query = 'yellow ball' 

我々は今、我々は、最も近いマッチを取得することができ、私たちの選択や入力を設定しました。

>>> process.extract(query, choices) 
[('red_ball', 53), ('green_ball', 48), ('red_cup', 13), ('green_cup', 10)] 

これは、一致の近さの降順ですべての選択肢を返します。文字列間の距離は、Levenshtein距離メトリックを使用して計算されます。上部のnアイテムを抽出し、有効な選択肢としてと指定することができます。の入力が選択肢セットに存在しない場合。あなただけのトップ試合をしたい場合は

、ちょうどこの操作を行います。

>>> process.extractOne(query, choices) 
('red_ball', 53) 

あなたはhereにマッチファジー文字列を使用してより多くの例を閲覧することができます。

1

プログラムの書き換え。正規表現を削除しました。アンダースコアやスペースを単語セパレータとして使用するかどうかはわかりませんでした(これは簡単に変更できます)。

SET = ('red ball', 'green ball', 'red cup', 'green cup') 

# For each element in the set, build a list of words 
WORDS = {} 
for s in SET: 
    WORDS[s] = list(s.split(' ')) 

# get user input 
user_input = 'yellow ball' 

if user_input not in SET: 
    # determine possible answers 
    input_words = user_input.split(' ') 
    other_answers = [] 
    for s in WORDS: 
    if any(w in WORDS[s] for w in input_words): 
     other_answers.append(s) 
    # print result 
    if len(other_answers) > 0: 
    print "'%s' not found, did you mean %s" % (
     user_input, 
     ", or ".join(["'%s'" % oa for oa in other_answers]) 
    ) 
    else: 
    print "'%s' not found" % user_input