Home > Mobile >  Count the input word in a List in Python
Count the input word in a List in Python

Time:12-29

enter image description here Why my code is not working properly ? It's not counting the word correctly.

Note: The code doesn't needs to be used for.

    list1 = input().split(sep=',')
    aim_count = list1.count('Enter aimed word to be counted: ')
    print('The count of aimed word: ', aim_count)

CodePudding user response:

    list1 = list(map(str.strip, input().split(sep=',')))
    aim_count = list1.count(input('Enter aimed word to be counted: ').strip())
    print('The count of aimed word: ', aim_count)

Here you are striping every word obtained from splitting using str.strip

CodePudding user response:

You are splitting your sentence by , but in your input, there is no ,

Try this:

list1 = input().split()
aim_count = len(list1)
print('The count of aimed word: ', aim_count)

Note: by default .split() method splits the sentence by space.

EDIT: If you want to count the no of a specific word.

try this:

list1 = input().split()

aim word = 'frog'

aim_count = 0
for word in list1:
    if word == aim_word:
        aim_count  = 1


print('The count of aimed word: ', aim_count)

CodePudding user response:

Try the following code to count the number of frogs entered

Input text: frog,frog

Code:

list1 = input().split(sep=',')
aim_count = list1.count('frog')
print('The count of aimed word: ', aim_count)

Output:

The count of aimed word:  2

Note:

When the input is frog,cat, the count of the aimed word is 1

Also if you want the aimed word to be dynamic: you can use this code:

list1 = input().split(sep=',')
aimed_word = input('Enter aimed word to be counted:')
aim_count = list1.count(aimed_word)
print('The count of aimed word: ', aim_count)

Note2:

If you plan to separate the words by comma and a space, then you should be splitting by that delimiter. ie. a comma then a space like this:

list1 = input().split(sep=', ')

CodePudding user response:

list's in-build count method takes in the element to be counted, meaning you cannot use 'Enter aimed word to be counted: ' as the element. You'll need to assign the input() to a variable and set that as the element to be counted. You'd need to do something along the lines of:-

aim_count = list1.count(input('Enter aimed word to be counted: '))

You might also be encountering a mismatch due to whitespaces which you can resolve with:-

list1 = input().split(sep=',')
list1 = [s.strip() for s in list1]

to remove all whitespaces between the words.

Alternatively, you could always use the string in-build count function instead.

aim_count = input('Enter sentence: ').count(input('Enter aimed word to be counted: '))
print('The count of aimed word: ', aim_count)
  • Related