14

比較で特殊文字の違いが無視されるように、2 つの文字列を比較したいと考えています。あれは、

ハイ、これはテストです

と一致する必要があります

ハイ!これはテストです」または「はい、これはテストです」

元の文字列を変更せずにこれを行う方法はありますか?

4

8 に答える 8

19

これにより、比較を行う前に句読点と空白が削除されます。

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
于 2013-05-10T03:54:04.557 に答える
10
>>> 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 つの一時リストが作成されますが、元の文字列はまったく変更されません。

于 2013-05-10T03:53:49.240 に答える
1

アルファベットの同等性について任意の数の文字列を比較するには、

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<=引数なしで何を返したいかによって変更する必要があります。

于 2013-05-10T04:30:25.890 に答える
1

通常、無視したい文字を置き換えてから比較します。

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
于 2013-05-10T03:53:56.180 に答える
0

元の文字列を変更したくないと述べているので、余分なスペースを必要とせずに操作をインプレースで行うこともできます。

>>> 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
于 2013-05-10T03:59:51.617 に答える
0

おそらく、最初に 2 つの文字列の特殊文字を削除してから、それらを比較できます。

あなたの例では、特殊文字は「、」、「!」です。とスペース。

だからあなたの文字列のために:

a='Hai, this is a test'
b='Hai ! this is a test'
tempa=a.translate(None,',! ')
tempb=b.translate(None,',! ')

次に、tempa と tempb を比較します。

于 2013-05-10T03:54:40.427 に答える
-1

レーベンシュタイン メトリックを使用して、2 つの文字列間の距離を測定します。文字列比較をスコアでランク付けします。上位n件の一致を選択します。

于 2013-05-10T03:57:11.843 に答える