wahlaoeh
wahlaoeh

Reputation: 55

Python Function to look for words in any provided sentence

I am new to programming and I just started learning Python by doing online classes at work. I am currently on the topic of writing a function. I thought that it will be useful to have a function that I can use to allow me to search for words in any string of text that is provided.

def searchword(enterprise, customer):
if "enterprise" exist:
    result = True
else: 
    result = False
    

I am not sure how to write the function to search for 2 words "enterprise" and "customer". And I am not sure how to define it that it will look for the words in a sentence string.

My mentor at work gave me the following function to validate that my above function works but I have not been able to get it to work.

def check_searchword():
assert searchword(True, True), "StarFox is an enterprise client."
print('Correct')

Upvotes: 1

Views: 1991

Answers (5)

John Doe
John Doe

Reputation: 1

Just do this:

key_words = ["enterprise", "customer"]
userInput = input("How may I help you?")

for word in userInput.split()
   if word in key_words:
      return true
   else:
      return false

Stuff like this may help. If it isn't or anything is wrong, plz tell me cuz im also a beginner! 😀

Upvotes: 0

Prakersh Maheshwari
Prakersh Maheshwari

Reputation: 1

To split a string to list of all words, I'll use string1.split()

In python string1 in list1, returns True if string1 is present in list1, else False.

# This function is used to search a word in a string.
# it returns True if search_key is present in search_string. 
# else False.

def searchword(search_key, search_string):
    search_list = search_string.split()
    return search_key in search_list 

search_s = "StarFox is an enterprise client."
print( searchword("enterprise", search_s) ) 

Upvotes: 0

Grismar
Grismar

Reputation: 31379

Learning how to program is all about learning to break down a problem into steps that can be further broken down, etc. until you reach steps for which single commands or statements exist. And for each step to be really specific - be your own devil's advocate.

If you're programming for a job, the trick is to know about many well-maintained libraries that allow you to code for more complicated steps in a single statement, instead of having to code everything yourself, but as a beginner, coding it yourself can be instructive.

If you're learning about using functions, the key thing to learn is that a function is more useful if it is more general, but not so general that it becomes needlessly complicated for simple uses.

You propose a function that searches for words in a provided string. The example you give seems to work for two specific words (and only those two). Something more general would be a function that searches for any number of words in a provided string.

If you break down the problem of finding multiple words in a string, the most obvious step is you'll need to find a single word in a string and perform that task for each of those words. If all of them are found, the result should be True, otherwise it should be False.

Something as simple as this works in Python:

>>> 'test' in 'this was a test'
True

Although this may show you need something else:

>>> 'is' in 'this was a test'
True

is is a part of this, so that may not be what you want. Be specific - do you only want to match whole words, or parts of words? If you only want whole words, you now have a new task: break up a string in whole words.

Something like this:

>>> 'is' in 'this was a test'.split()
False
>>> 'test' in 'this was a test'.split()
True

If you need to do this for multiple things again and again, a loop sounds obvious:

>>> text = 'this was a test'
>>> result = True
>>> for word in ['test', 'was']:
...      result = result and word in text.split()

And if your task is to capture that in a function, the function should receive everything it needs to do its job through its arguments (the string and the words to look for) and it should return everything you expect from it (a single boolean value).

def search_words(text, words):
    result = True
    for word in words:
        result = result and word in text.split()
    return result

print(search_words('this was a test', ['was', 'test']))

That works, but it's not very efficient, since it splits text again and again, once for each word. Also, to the trained Python eye, it doesn't look very 'pythonic', which generally means writing it in clear and easy to read Python that builds on Python's strengths as a language.

For example:

def search_words(text, words):
    text_words = text.split()
    return all(word in text_words for word in words)

print(search_words('this was a test', ['was', 'test']))

Of course, another important aspect of programming is meeting your client's specifications. If they insist they want a function that searches for those two specific words, using only the text as a parameter, you could use the above function to quickly give them just that:

def client_search_words(text):
    return search_words(text, ['enterprise', 'customer'])


assert client_search_words('StarFox is an enterprsise client'), True

This will throw an assertion error, because it asserts something that is False (the result of the function is not True).

I don't think working with assertions here is a very good way to go though, that's a part of Python that's typically far less important than the stuff you want to deal with right now.

Upvotes: 1

David Warren
David Warren

Reputation: 179

Great starting project - a couple of things to note. First off, Python works off indentation, which is one reason why your mentors function isn't working.

Another approach is to use a for loop, which will iterate over each item in the list and do the check. For example:

test ="StarFox is an enterprise client."
searchword = ['enterprise', 'customer']

for i in searchword:
  print(i in test) #please note, this will look for the grouping of letters and not a direct work match. So the loop will see 'enterprise' and 'enterprises' as the same thing

Finally, this type of text checking is better off done with regex. There are loads of tutorials online for this - the book Automate the Boring Stuff is a great resource, as are a number of blog posts such as this one from Towards Data Science

Upvotes: 1

Anmol Parida
Anmol Parida

Reputation: 688

import re

def searchword(customerString, searchFor="enterprise"):
    if re.search(searchFor, customerString):
        return True
    else:
        return False


assert searchword("StarFox is an enterprsise client."), True
assert searchword("StarFox is an enxerprsexe client."), True >> Throws AssertionError: True

Upvotes: 1

Related Questions