user152574
user152574

Reputation: 15

Counting words in a String in Python

I need to write a program that asks for a letter and also an input. I need to find the number of the words that contains that specific letter and also lists those words. So far i have been able to list the words that contain that specific letter however i can't find the amount of words that contain this specific letter.

So far my code is:

a = input("Letter: ")  
b = input("Input: ")  
a=a.lower() 
b=b.lower()  
c=b.count(a)
print(c)  
words = b.split()  
print(' '.join([word for word in words if a in word]))

And the output is this:

Letter: e 
Input: ee eeeee the 
8 
ee eeeee the

However, the answer should be 3 not 8 as only 3 words contain the letter 'e'.

So, can i get any help in fixing my problem.

Thanks.

Upvotes: 1

Views: 2239

Answers (5)

Padraic Cunningham
Padraic Cunningham

Reputation: 180540

a ="ee eeeee the"

print sum("e" in x for x in a.split())
3

Split the words and check if e is in each word and use sum to get the total.

b.count(a) is counting every occurrence of the letter.

In [1]: a ="ee eeeee the"

In [2]: a.split()
Out[2]: ['ee', 'eeeee', 'the'] # splits into individual words
In [3]: sum("e" in x for x in a.split()) # e is in all three words so sum returns 3
Out[3]: 3

You can also change your code and use len()

final_words = [word for word in words if a in word]
c = len(final_words)
print c
final  = (' '.join(final_words))
print final

Upvotes: 4

You were pretty close, except that you should count the number of elements in the list you create in the last line. This should work instead:

a = input("Letter: ")  
b = input("Input: ")  
a=a.lower() 
b=b.lower()  
words = [word for word in b.split() if a in word]  
print(len(words))
print(' '.join(words))

Upvotes: 2

tarjei
tarjei

Reputation: 46

Change c=b.count(a) to something like c = sum(a in word for word in b.split())

Upvotes: 0

dugres
dugres

Reputation: 13113

found = [word for word in words if a in word]
num = len(found)

print num
print ' '.join(found)

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 118021

The way you currently wrote it, you are counting all occurences of the letter e. You just need to check if the word contains the letter, then move on to the next word.

>>> a = 'a'
>>> s = 'aaa bbb ccc ddd eaa faa abc'

>>> words = s.split()
>>> words
['aaa', 'bbb', 'ccc', 'ddd', 'eaa', 'faa', 'abc']

>>> len(filter(lambda i : a in i, words))
4

As a function

def wordCounter(letter, sentence):
    wordList = sentence.split()
    return len(filter(lambda word : letter in word, wordList))

Testing the function

>>> wordCounter(a, s)
4

>>> wordCounter('e', 'ee eeeee the')
3

Upvotes: 1

Related Questions