2

Let's say that I am looking for the word "or". What I want is to check whether that word appears as a word or as a substring of another word.

E.g.

Input - "or" Output - "true"

Input - "for" Output - "false"

I suppose I could check if the chars before and after are letters but is there a more efficient/easier way of doing it? Thanks

Edit In addition, the string will be part of a sentence. So I want "I can go shopping or not" to return true but "I can go shopping for shoes" to return false. Therefore using == wouldn't work. I'm sorry I should've mentioned this earlier

Dan
  • 527
  • 4
  • 16
  • 5
    If it's just one word why don't you just use `==`? – Farhan.K Dec 11 '17 at 18:10
  • 1
    It is because it is part of a sentence not just one word. For example I want "I can go shopping or not" to return true but "I can go shopping for shoes" to return false. So using == wouldn't work. I'm sorry I should've mentioned this in the question. – Dan Dec 11 '17 at 18:14

4 Answers4

4

Use a regex.

>>> import re
>>> re.search(r'\bor\b', 'or')
<_sre.SRE_Match object at 0x7f445333a5e0>
>>> re.search(r'\bor\b', 'for')
>>> 
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

You can use a regular expression for this:

import re

def contains_word(text, word):
    return bool(re.search(r'\b' + re.escape(word) + r'\b', text))

print(contains_word('or', 'or')) # True
print(contains_word('for', 'or')) # False
print(contains_word('to be or not to be', 'or')) # True
Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
1

Create a checker with just a test if it is in the line

def check_word_in_line(word, line):
    return " {} ".format(word) in line

print(check_word_in_line("or", "I can go shopping or not")) //True
print(check_word_in_line("or", "I can go shopping for shoes")) //False
Ivonet
  • 2,492
  • 2
  • 15
  • 28
0

You can use the nltk (Natural Language Toolkit) to split the sentence into words, and then check if some word exists with ==.

NLTK Installation

NLTK Package Download

import nltk

def checkword(sentence):
    words = nltk.word_tokenize(sentence)
    return any((True for word in words if word == "or"))

print(checkword("Should be false for."))
print(checkword("Should be true or."))
clfaster
  • 1,450
  • 19
  • 26
  • 1
    I've edited your answer for two reasons: 1. there is no need to write `else` after an `if` followed by a `return`, because you can only return from a function once; 2. there is no need in the `if/else` clause when you want to return a boolean based on a condition, because the condition itself is a boolean. – Eli Korvigo Dec 11 '17 at 18:18