Saturday, January 5, 2019

codingdirectional: Count the words within a string with python

Hello and nice to meet you all again. In this article, we will continue to solve the problem on the py.checkio.org website. This website has provided a great opportunity for those python programmers that want to see how good their python skills really are by allowing them to solve various programming problems with python. Just like what I had mentioned before, I am still in the stage of finding it out what else does this site has to offer besides asking us to solve python related questions but before I can go even further I need to solve some basic problems first. In this article, we will solve the below problem with python.

Given a string as the first parameter and a set of lowercase words as the second parameter of a function, find out how many words in that set have appeared in the given string. The program will need to convert the string to the lowercase letter’s string first because this is not a case-sensitive comparison.

def count_words(text: str, words: set):
    word_list = list(words)
    count = 0
    for i in range(len(word_list)):
        
        if(word_list[i] in text.lower()):
            print(word_list[i])
            count+=1
    return count

print(count_words("Lorem ipsum dolor sit amet, consectetuer adipiscing elit.",
                       {"sum", "hamlet", "infinity", "anything"}))

The above program will output these values with above inputs: sum, 1, as you can see that program will search for those words in the set in each word and partial word of the given string.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...