I am trying to complete something for my first ever python class. I turned a given string into a list and then made a loop to count the number of 'to' contained in the list. However, it comes out as individual '1's and I need the answer to be the total word_count == 4 somehow.
Input:
print(words)
word_count = 0
for target_word in words:
if (target_word == 'to'):
print(word_count 1)
Output:
['to', 'split;', 'bill', 'to', 'lint', 'to', 'leads', 'to', 'suffer']
1
1
1
1
thanks to anyone for their help. I am in a different timezone and cannot contact my admin for help atm.
CodePudding user response:
words = text.split()
print(words)
word_count = 0
for target_word in words:
if (target_word == 'to'):
word_count = 1
print(word_count)
An even simpler approach would be
print(words.count("to"))
If you want to get a summary of words, then:
from collections import Counter
c = Counter(words)
print(c)
CodePudding user response:
Previous post is great - showing different ways to do the counts. Here it's another one just for reference - it's using generator expression to quickly count, if we're not interested in the intermediate results, but just the final answer.
>>> words = ['to', 'split;', 'bill', 'to', 'lint', 'to', 'leads', 'to', 'suffer']
>>> search = 'to'
>>> count = sum(1 for w in words if w == search)
>>> count
4