比較で特殊文字の違いが無視されるように、2 つの文字列を比較したいと考えています。あれは、
ハイ、これはテストです
と一致する必要があります
ハイ!これはテストです」または「はい、これはテストです」
元の文字列を変更せずにこれを行う方法はありますか?
比較で特殊文字の違いが無視されるように、2 つの文字列を比較したいと考えています。あれは、
ハイ、これはテストです
と一致する必要があります
ハイ!これはテストです」または「はい、これはテストです」
元の文字列を変更せずにこれを行う方法はありますか?
これにより、比較を行う前に句読点と空白が削除されます。
In [32]: import string
In [33]: def compare(s1, s2):
...: remove = string.punctuation + string.whitespace
...: return s1.translate(None, remove) == s2.translate(None, remove)
In [34]: compare('Hai, this is a test', 'Hai ! this is a test')
Out[34]: True
>>> def cmp(a, b):
... return [c for c in a if c.isalpha()] == [c for c in b if c.isalpha()]
...
>>> cmp('Hai, this is a test', 'Hai ! this is a test')
True
>>> cmp('Hai, this is a test', 'Hai this is a test')
True
>>> cmp('Hai, this is a test', 'other string')
False
これにより、2 つの一時リストが作成されますが、元の文字列はまったく変更されません。
アルファベットの同等性について任意の数の文字列を比較するには、
def samealphabetic(*args):
return len(set(filter(lambda s: s.isalpha(), arg) for arg in args)) <= 1
print samealphabetic('Hai, this is a test',
'Hai ! this is a test',
'Hai this is a test')
どちらが印刷されますかTrue
。<=
引数なしで何を返したいかによって変更する必要があります。
通常、無視したい文字を置き換えてから比較します。
import re
def equal(a, b):
# Ignore non-space and non-word characters
regex = re.compile(r'[^\s\w]')
return regex.sub('', a) == regex.sub('', b)
>>> equal('Hai, this is a test', 'Hai this is a test')
True
>>> equal('Hai, this is a test', 'Hai this@#)($! i@#($()@#s a test!!!')
True
元の文字列を変更したくないと述べているので、余分なスペースを必要とせずに操作をインプレースで行うこともできます。
>>> import string
>>> first = "Hai, this is a test"
>>> second = "Hai ! this is a test"
>>> third = "Hai this is a test"
>>> def my_match(left, right):
i, j = 0, 0
ignored = set(string.punctuation + string.whitespace)
while i < len(left) and j < len(right):
if left[i] in ignored:
i += 1
elif right[j] in ignored:
j += 1
elif left[i] != right[j]:
return False
else:
i += 1
j += 1
if i != len(left) or j != len(right):
return False
return True
>>> my_match(first, second)
True
>>> my_match(first, third)
True
>>> my_match("test", "testing")
False
おそらく、最初に 2 つの文字列の特殊文字を削除してから、それらを比較できます。
あなたの例では、特殊文字は「、」、「!」です。とスペース。
だからあなたの文字列のために:
a='Hai, this is a test'
b='Hai ! this is a test'
tempa=a.translate(None,',! ')
tempb=b.translate(None,',! ')
次に、tempa と tempb を比較します。
レーベンシュタイン メトリックを使用して、2 つの文字列間の距離を測定します。文字列比較をスコアでランク付けします。上位n件の一致を選択します。