Python – Controleer of woord in A String

Ik ben bezig met Python v2, en ik probeer uit te vinden of je kunt zien of een woord in een string.

Ik heb wat informatie over het herkennen als het woord in de string gevonden – met behulp van .Vind, maar is er een manier om een ​​doen als statement. Ik zou graag iets als het volgende:

if string.find(word):
    print 'success'

Bedankt voor alle hulp.


1, Autoriteit 100%

Wat is er mis met:

if word in mystring: 
   print 'success'

2, Autoriteit 46%

if 'seek' in 'those who seek shall find':
    print('Success!')

maar houd er rekening mee dat dit overeenkomt met een reeks tekens, niet per se een heel woord – bijvoorbeeld 'word' in 'swordsmith'is True. Als je alleen wilt hele woorden te passen, moet je reguliere expressies te gebruiken:

import re
def findWholeWord(w):
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search
findWholeWord('seek')('those who seek shall find')    # -> <match object>
findWholeWord('word')('swordsmith')                   # -> None

3, Autoriteit 14%

Als u wilt weten of een heel woord is in een door spaties gescheiden lijst van woorden, eenvoudig te gebruiken:

def contains_word(s, w):
    return (' ' + w + ' ') in (' ' + s + ' ')
contains_word('the quick brown fox', 'brown')  # True
contains_word('the quick brown fox', 'row')    # False

Deze elegante methode is ook de snelste. Vergeleken met de benaderingen van Hugh Bothwell en daSong:

>python -m timeit -s "def contains_word(s, w): return (' ' + w + ' ') in (' ' + s + ' ')" "contains_word('the quick brown fox', 'brown')"
1000000 loops, best of 3: 0.351 usec per loop
>python -m timeit -s "import re" -s "def contains_word(s, w): return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search(s)" "contains_word('the quick brown fox', 'brown')"
100000 loops, best of 3: 2.38 usec per loop
>python -m timeit -s "def contains_word(s, w): return s.startswith(w + ' ') or s.endswith(' ' + w) or s.find(' ' + w + ' ') != -1" "contains_word('the quick brown fox', 'brown')"
1000000 loops, best of 3: 1.13 usec per loop

Bewerken:Een kleine variant op dit idee voor Python 3.6+, even snel:

def contains_word(s, w):
    return f' {w} ' in f' {s} '

Antwoord 4, autoriteit 5%

find geeft een geheel getal terug dat de index vertegenwoordigt van waar het zoekitem is gevonden. Als het niet wordt gevonden, retourneert het -1.

haystack = 'asdf'
haystack.find('a') # result: 0
haystack.find('s') # result: 1
haystack.find('g') # result: -1
if haystack.find(needle) >= 0:
  print 'Needle found.'
else:
  print 'Needle not found.'

Antwoord 5, autoriteit 4%

Je kunt de tekenreeks splitsen in de woorden en de resultatenlijst controleren.

if word in string.split():
    print 'success'

Antwoord 6, autoriteit 3%

Deze kleine functie vergelijkt alle zoekwoorden in bepaalde tekst. Als alle zoekwoorden in tekst worden gevonden, wordt de zoekduur geretourneerd, of anders False.

Ondersteunt ook zoeken naar unicode-tekenreeksen.

def find_words(text, search):
    """Find exact words"""
    dText   = text.split()
    dSearch = search.split()
    found_word = 0
    for text_word in dText:
        for search_word in dSearch:
            if search_word == text_word:
                found_word += 1
    if found_word == len(dSearch):
        return lenSearch
    else:
        return False

gebruik:

find_words('çelik güray ankara', 'güray ankara')

Antwoord 7, autoriteit 2%

Als het matchen van een reeks tekens niet voldoende is en u hele woorden moet matchen, is hier een eenvoudige functie die de klus klaart. Het voegt in feite spaties toe waar nodig en zoekt daarnaar in de string:

def smart_find(haystack, needle):
    if haystack.startswith(needle+" "):
        return True
    if haystack.endswith(" "+needle):
        return True
    if haystack.find(" "+needle+" ") != -1:
        return True
    return False

Hierbij wordt ervan uitgegaan dat komma’s en andere leestekens al zijn verwijderd.


8

Geavanceerde manier om het exacte woord te controleren, dat we in een lange string moeten vinden:

import re
text = "This text was of edited by Rock"
#try this string also
#text = "This text was officially edited by Rock" 
for m in re.finditer(r"\bof\b", text):
    if m.group(0):
        print "Present"
    else:
        print "Absent"

9

Zoals u om een ​​woord vraagt ​​en niet voor een reeks, zou ik een oplossing willen presenteren die niet gevoelig is voor voorvoegsels / achtervoegsels en het negeert:

#!/usr/bin/env python
import re
def is_word_in_text(word, text):
    """
    Check if a word is in a text.
    Parameters
    ----------
    word : str
    text : str
    Returns
    -------
    bool : True if word is in text, otherwise False.
    Examples
    --------
    >>> is_word_in_text("Python", "python is awesome.")
    True
    >>> is_word_in_text("Python", "camelCase is pythonic.")
    False
    >>> is_word_in_text("Python", "At the end is Python")
    True
    """
    pattern = r'(^|[^\w]){}([^\w]|$)'.format(word)
    pattern = re.compile(pattern, re.IGNORECASE)
    matches = re.search(pattern, text)
    return bool(matches)
if __name__ == '__main__':
    import doctest
    doctest.testmod()

Als uw woorden RGEX Special Chars (zoals +) kunnen bevatten, dan heeft u re.escape(word)

nodig


10

Hoe zit het met het splitsen van de string en strip woorden interpunctie?

w in [ws.strip(',.?!') for ws in p.split()]

Doe indien nodig, aandacht aan lagere / hoofdletters:

w.lower() in [ws.strip(',.?!') for ws in p.lower().split()]

Misschien op die manier:

def wcheck(word, phrase):
    # Attention about punctuation and about split characters
    punctuation = ',.?!'
    return word.lower() in [words.strip(punctuation) for words in phrase.lower().split()]

Sample:

print(wcheck('CAr', 'I own a caR.'))

Ik heb de prestaties niet gecontroleerd …


11

Je zou gewoon een spatie kunnen toevoegen voor en na “woord”.

x = raw_input("Type your word: ")
if " word " in x:
    print "Yes"
elif " word " not in x:
    print "Nope"

Op deze manier zoekt het naar de spatie voor en na “woord”.

>>> Type your word: Swordsmith
>>> Nope
>>> Type your word:  word 
>>> Yes

Other episodes