How to count the occurrences of each word in a string with Python

1 Answer

0 votes
def word_occurrences(str):
    counts = dict()
    words = str.split()

    for word in words:
        if word in counts:
            counts[word] += 1
        else:
            counts[word] = 1

    return counts

s = "programming is python is c is a java high level c programming c python"

print(word_occurrences(s))


 
 
'''
run:
 
{'programming': 2, 'is': 3, 'python': 2, 'c': 3, 'a': 1, 'java': 1, 'high': 1, 'level': 1}

'''

 



answered Aug 31, 2021 by avibootz

Related questions

...