Match exact phrase within a string in Python

后端 未结 5 542
梦如初夏
梦如初夏 2020-12-18 10:13

I\'m trying to determine whether a substring is in a string. The issue I\'m running into is that I don\'t want my function to return True if the substring is found within an

相关标签:
5条回答
  • 2020-12-18 10:30

    One can do this very literally with a loop

    phrase = phrase.lower()
    text = text.lower()
    
    answer = False 
    j = 0
    for i in range(len(text)):
        if j == len(phrase):
            return text[i] == " "
        if phrase[j] == text[i]:
            answer = True
            j+=1
        else:
            j = 0 
            answer = False 
    return answer
    

    Or by splitting

    phrase_words = phrase.lower().split()
    text_words = text.lower().split()
    
    return phrase_words in text_words
    

    or using regular expressions

    import re
    pattern = re.compile("[^\w]" + text + ""[^\w]")
    pattern.match(phrase.lower())
    

    to say that we want no characters preceding or following our text, but whitespace is okay.

    0 讨论(0)
  • 2020-12-18 10:31

    Since your phrase can have multiple words, doing a simple split and intersect won't work. I'd go with regex for this one:

    import re
    
    def is_phrase_in(phrase, text):
        return re.search(r"\b{}\b".format(phrase), text, re.IGNORECASE) is not None
    
    phrase = "Purple cow"
    
    print(is_phrase_in(phrase, "Purple cows make the best pets!"))   # False
    print(is_phrase_in(phrase, "Your purple cow trampled my hedge!"))  # True
    
    0 讨论(0)
  • 2020-12-18 10:39

    Regular Expressions should do the trick

    import re
    
    def is_phrase_in(phrase, text):
        phrase = phrase.lower()
        text = text.lower()
        if re.findall('\\b'+phrase+'\\b', text):
            found = True
        else:
            found = False
        return found
    
    0 讨论(0)
  • 2020-12-18 10:48

    Using PyParsing:

    import pyparsing as pp
    
    def is_phrase_in(phrase, text):
        phrase = phrase.lower()
        text = text.lower()
    
        rule = pp.ZeroOrMore(pp.Keyword(phrase))
        for t, s, e in rule.scanString(text):
          if t:
            return True
        return False
    
    text = "Your purple cow trampled my hedge!"
    phrase = "Purple cow"
    print(is_phrase_in(phrase, text))
    

    Which yields:

    True
    
    0 讨论(0)
  • 2020-12-18 10:53

    Here you go, hope this helps

     # Declares
     string = "My name is Ramesh and I am cool. You are Ram ?"
     sub = "Ram"
    
     # Check String For SUb String
     result = sub in string
    
     # Condition Check
     if result:
    
        # find starting position
        start_position = string.index(sub)
    
        # get stringlength
        length = len(sub)
    
        # return string
        output = string[start_position:len]
    
    0 讨论(0)
提交回复
热议问题