You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 10:37:27