简体   繁体   中英

Finding a word in just a sentence and not in a word (python)

In Python im trying to find a word in a sentece by using:

if word in sentence:
    number = number + 1

This works fine for finding a word in a sentence, the problem im running into is that this code finds the word inside other words. For example:

word = "or"
sentence = "Python or Java use a lot of words"
if word in sentence:
    number = number + 1

number will equal 2 instead of 1 because "or" is after "Python" and before "Java", and it also finds "or" in the word "word" Im trying to find a way to find just the word "or" by itself, instead of the program finding it in the sentence and in another word.

"Python or Java use a lot of words".lower().split().count('or')

should do it.

lower converts all of the text to lower case, split turns it into a list (space is the default delimiter) then count does a count against the list.

You need to split the sentence first using str.split :

>>> sentence = "Python or Java use a lot of words"
>>> sentence.split()
['Python', 'or', 'Java', 'use', 'a', 'lot', 'of', 'words']
>>>

This will give you a list of the words. After that, your code will work:

>>> # I made this so I didn't get a NameError
>>> number = 0
>>> word = "or"
>>> sentence = "Python or Java use a lot of words"
>>> if word in sentence.split():
...     # This is the same as "number = number + 1"
...     number += 1
...
>>> number
1
>>>

You can try splitting the sentence first, as so

if word in sentence.split(" "):

This will split sentence into an array of words, assuming all the words are separated by a single space. This is equivalent to using

if word in [ "Python", "or", "Java", "use", "a", "lot", "of", "words" ]:

which will check if the whole word exists in the list, rather than checking for substrings in the original sentence

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM