Ugbuk
Ugbuk

Reputation: 47

How to find every instance of a word in a tuple python?

School task to find how many times does word input by user repeats in tuple. My code finds every word but if i put a sentence containing two of the same words that user is looking for it still returns 1 as print(). Im new in the vast programming world so please take it into consideration. I dont know how to name all things properly. :<

tuple=("one","two","three","four","five","six","one cat one dog")
word=input("Input word: ")
count=0
for i in tuple:
    if word in i and len(word)>1:
        count += 1
if count!=0:
    print("This word repeats this many times: ",count)
else:
    print("There are no words that match user input")

Upvotes: 3

Views: 377

Answers (3)

Arifa Chan
Arifa Chan

Reputation: 1017

You can try using joinand count:

tup = ("one","two","three","four","five","six","one cat one dog")

word = input("Input word: ")
count = ' '.join(tup).count(word)

if count: print("This word repeats this many times: ", count)
else: print("There are no words that match user input")

# Input word: one
# This word repeats this many times:  3

Upvotes: 0

Conor Romano
Conor Romano

Reputation: 150

If you want to convert it to a function you can use the below code. It loops through all of the items in the tuple, and if it's a string, increments the count by the number of times the word appears.

_tuple = ("one", "two", "three", "four", "five", "six", "one cat one dog")

# function to count the number of times word appears in tuple
def tuple_word_count(item, phrase_tuple):
    count = 0

    for item in phrase_tuple:
        if isinstance(item, str):
            count = count + item.count(word)

    if count != 0:
        return str("This word repeats this many times: " + str(count))
    else:
        return str("There are no words that match user input")

user_word=input("Input word: ")

print(tuple_word_count(user_word, _tuple))

Upvotes: 2

Adon Bilivit
Adon Bilivit

Reputation: 27163

The collections module has a Counter class that is very useful for this kind of problem.

However, if you don't want to import anything then you can do it like this:

_tuple = ("one", "two", "three", "four", "five", "six", "one cat one dog")

counter = {}

for element in _tuple:
    for word in element.split():
        counter[word] = counter.get(word, 0) + 1

word = input('Input word: ')

print(f'{word} occurs {counter.get(word, 0)} times')

If you want to use Counter then you could do this:

from collections import Counter

_tuple = ("one", "two", "three", "four", "five", "six", "one cat one dog")

def get_words(iterable):
    for item in iterable:
        for word in item.split():
            yield word

counter = Counter(get_words(_tuple))

word = input('Input word: ')

print(f'{word} occurs {counter[word]} times')

Upvotes: 1

Related Questions