【问题标题】:Count unique words and create dict with word and count in Python在 Python 中计算唯一单词并使用单词和计数创建 dict
【发布时间】:2012-10-02 03:22:43
【问题描述】:

我需要帮助创建一个名为strcount(S) 的函数,该函数返回一个字典,其中单词作为键,单词出现的次数作为相应的值。输出应该是这样的:

strcount("a a a a b b")
{'a': 4, 'b': 2}
strcount("one")
{'one': 1}
sorted(strcount("this one and that one for one time").items())
[('and', 1), ('for', 1), ('one', 3), ('that', 1), ('this', 1), ('time', 1)]

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    最 Pythonic 的解决方案是使用 collections.Counter:

    >>> from collections import Counter
    >>> Counter("this one and that one for one time".split()).items()
    [('and', 1), ('for', 1), ('that', 1), ('this', 1), ('one', 3), ('time', 1)]
    

    如果你想编写自己的解决方案,我会尝试这样的:

    1. 将字符串拆分为单词列表。您可以为此使用.split()
    2. 构造一个字典,其中每个键为一个单词,值为0
    3. 遍历您的单词列表。对于每个单词,将1 添加到your_dict[word]

    【讨论】:

      【解决方案2】:

      或者,您可以在不使用 Counter 的情况下实现自己的算法。

      def countwords(A):  
          dic = {}  
          for item in A.split():  
             if dic.has_key(item):  
                 dic[item] += 1  
             else:  
                 dic[item] = 1  
      
          return sorted(dic.items())  # return sorted list.
      

      如果您使用的是 Python 3.x,请替换以下行:

      if dic.has_key(item):
      

      与:

      if item in dic:
      

      输出:

      >>> print (countwords("this one and that one for one time"))
      [('and', 1), ('for', 1), ('one', 3), ('that', 1), ('this', 1), ('time', 1)]
      

      【讨论】:

        【解决方案3】:

        @Blender 使用 Counter 的答案很棒,但它适用于 Python 2.7 及更高版本。

        这是适用于较低版本 Python 的替代解决方案:

        from collections import defaultdict
        
        word_freq = defaultdict(int)
        for i in "this one and that one for this one".split():
           word_freq[i] += 1
        

        这会给你:

        >>> word_freq
        defaultdict(<type 'int'>, {'this': 2, 'and': 1, 'that': 1, 'for': 1, 'one': 3})
        >>> word_freq['one']
        3
        

        【讨论】:

          【解决方案4】:

          我会这样做:

          def strcount(input):
              d = dict()
              for word in input:
                  if word not in d:
                      d[word] = 1
                  else:
                      d[word] += 1
              return d 
          

          这是我使用的一种简单方法,也适用于您。也许不是最快的,但绝对有效且简单。

          【讨论】:

            猜你喜欢
            • 2015-06-02
            • 2012-08-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-08-06
            • 1970-01-01
            • 1970-01-01
            • 2020-07-04
            相关资源
            最近更新 更多