2017-04-20 11 views
0

私はここで何かを尋ねるのは初めてです。これはとても新しいので、ベストを尽くします。私は似てすべてのフレーズを解消したい、語句のリストを持っている、よう:文字列のリスト内の要素を同様に削除する

array = ["A very long string saying some things", 
     "Another long string saying some things", 
     "extremely large string saying some things", 
     "something different", 
     "this is a test"] 

私はこの結果たい:

for i in range(len(array)): 
    swich=True 
    for j in range(len(array2)): 
     if (fuzz.ratio(array[i],array2[j]) >= 80) and (swich == True): 
      swich=False 
      pass 
     if (fuzz.ratio(array[i],array2[j]) >= 80) and (swich == False): 
      array2.pop(j) 

しかし:

array2 = ["A very long string saying some things", 
      "something different", 
      "this is a test"]` 

を私はこれを持っています私にリストを与えるIndexError ...

fuzzy.ratioは2つの文字列を比較し、値を与えるトゥイーン0と100の間では、大きいほど、文字列は似ています。

私がしようとしているのは、リストを要素ごとに比較することです。最初に2つの類似した文字列を見つけたら、スイッチをオンにして、同様の結果が得られたら、array2という要素をポップします。私は完全に任意の提案に開放されています。

+2

正確なエラートレースを...リストにはインデックスエラーがありますか? – rassar

答えて

0

エラーは、その時点で反復処理中のリストの変更によって発生します。 (現在繰り返されているイテレーターの要素を追加/削除/置き換えないでください)range(len(array2))は長さがNであることを知っていますが、array2.pop(j)の後では長さはNではなくN-1です。後でN番目の要素にアクセスしようとすると、リストが短くなるため、IndexErrorが返されます。

別のアプローチで迅速な推測:

original = ["A very long string saying some things", "Another long string saying some things", "extremely large string saying some things", "something different", "this is a test"] 

filtered = list() 

for original_string in original: 
    include = True 
    for filtered_string in filtered: 
     if fuzz.ratio(original_string, filtered_string) >= 80: 
      include = False 
      break 
    if include: 
     filtered.append(original_string) 

より「神託」で、何の整数変数や範囲を必要としないfor string in arrayループを、注意してください。

0

コードをコンパクトにしてループ数を減らすために、別のライブラリを使用することはどうですか?

import difflib 

def remove_similar_words(word_list): 
    for elem in word_list: 
     first_pass = difflib.get_close_matches(elem, word_list) 
     if len(first_pass) > 1: 
      word_list.remove(first_pass[-1]) 
      remove_similar_words(word_list) 
    return word_list 


l = ["A very long string saying some things", "Another long string saying some things", "extremely large string saying some things", "something different", "this is a test"] 

remove_similar_words(l) 

['A very long string saying some things', 
'something different', 
'this is a test'] 
関連する問題