如何在Python 3中统计字符串单词出现次数并基于指定类结构实现代码
Word Occurrence Count Implementation
To solve this problem, we can break down the task into simple, actionable steps:
- Split the input string into individual words using whitespace as the delimiter.
- Track how many times each word appears using a dictionary.
- Return the dictionary where keys are words and values are their respective occurrence counts.
Here's the complete implementation of the usermaincode class with the required word_occur class method:
class usermaincode(object): @classmethod def word_occur(cls, input1): # Empty dictionary to store word counts word_counts = {} # Split input string into a list of words words = input1.split() # Iterate through each word to update counts for word in words: if word in word_counts: word_counts[word] += 1 else: word_counts[word] = 1 return word_counts
Testing the Code
If you run this with your example input:
input1 = "Hello new new" print(usermaincode.word_occur(input1))
You’ll get the expected output: {'Hello': 1, 'new': 2}.
Quick Notes
- This implementation is case-sensitive (e.g., "Hello" and "hello" would be counted as separate words). If you need case-insensitive counting, just convert each word to lowercase before checking the dictionary:
word = word.lower(). - The
split()method handles multiple spaces between words automatically, so inputs with extra whitespace will still work correctly.
内容的提问来源于stack exchange,提问作者Vidya
相关产品推荐
相关产品推荐

