Python String Search Regardless Of Character Sequence

后端 未结 2 1271
粉色の甜心
粉色の甜心 2021-01-24 06:52

I want to create an application that checks if word that the user typed in contains word/words from a separate text file (e.g. input = \'teeth\', separate file contains the word

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-24 07:56

    I would create a collections.Counter object from both strings, counting the characters, then substract the dicts, test if resulting dict is empty (which means string contains substring with cardinality respected)

    import collections

    def contains(substring, string):
        c1 = collections.Counter(string)
        c2 = collections.Counter(substring)
        return not(c2-c1)
    
    print(contains("eeh","teeth"))
    print(contains("eeh","teth"))
    

    result:

    True
    False
    

    Note that your example isn't representative as

    >>> "eet" in "teeth"
    True
    

    that's why I changed it.

提交回复
热议问题