How python counts the number of occurrences of each word in a string
This article mainly introduces python how to count the number of occurrence of each word in the string, which is very detailed and has certain reference value. Friends who are interested must finish reading it!
Count the number of occurrences of each word in the string.
Def word_amount (sentence):
Split_list = sentence.split ()
Dict_result = {}
For word_name in split_list:
If word_name not in dict_result.keys ():
Dict_ result [word _ name] = 1
Else:
Dict_ result [word _ name] + = 1
Return dict_result
If _ _ name__ = ='_ _ main__':
Sentence = "I can because i think i can"
Dict_result = word_amount (sentence)
Print (dict_result)
Or:
If _ _ name__ = ='_ _ main__':
Sentence = "I can because i think i can"
Result = {word: sentence.split () .count (word) for word in set (sentence.split ())}
Print (result)
Or:
From collections import Counter
If _ _ name__ = ='_ _ main__':
Sentence = "I can because i think i can"
Counts = Counter (sentence.split ())
Print (counts)
The above is all the contents of the article "how python counts the number of occurrences of each word in a string". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!