【问题标题】:Counting the number of unique words in a list计算列表中唯一单词的数量
【发布时间】:2021-03-24 05:25:19
【问题描述】:

使用来自https://stackoverflow.com/a/11899925 的以下代码,我能够找到一个单词是否唯一(通过比较它是否使用过一次或多次):

helloString = ['hello', 'world', 'world']
count = {}
for word in helloString :
   if word in count :
      count[word] += 1
   else:
      count[word] = 1

但是,如果我有一个包含数百个单词的字符串,我将如何计算该字符串中唯一单词的数量?

例如,我的代码有:

uniqueWordCount = 0
helloString = ['hello', 'world', 'world', 'how', 'are', 'you', 'doing', 'today']
count = {}
for word in words :
   if word in count :
      count[word] += 1
   else:
      count[word] = 1

如何将uniqueWordCount 设置为6?通常,我真的很擅长解决这些类型的算法难题,但我没有成功解决这个问题。我觉得它就在我的鼻子下面。

【问题讨论】:

  • 唯一的词有 6 个,而不是 5 个
  • 7 个唯一词不是 6 个

标签: python python-3.x


【解决方案1】:

解决此问题的最佳方法是使用set 集合类型。 set 是一个集合,其中所有元素都是唯一的。因此:

unique = set([ 'one', 'two', 'two']) 
len(unique) # is 2

您可以从一开始就使用一个集合,然后在其中添加单词:

unique.add('three')

这将在添加任何重复项时丢弃它们。或者,您可以收集列表中的所有元素并将列表传递给set() 函数,该函数将在那时删除重复项。我上面提供的示例显示了这种模式:

unique = set([ 'one', 'two', 'two'])
unique.add('three')

# unique now contains {'one', 'two', 'three'}

Read more about sets in Python.

【讨论】:

    【解决方案2】:

    你有很多选择,我推荐一组,但你也可以使用计数器,它计算数字显示的数量,或者你可以查看你制作的字典的键数。


    设置

    您还可以将列表转换为集合,其中所有元素都必须是唯一的。不唯一的元素被丢弃:

    helloString = ['hello', 'world', 'world', 'how', 'are', 'you', 'doing', 'today']
    helloSet = set(helloString) #=> ['doing', 'how', 'are', 'world', 'you', 'hello', 'today']
    uniqueWordCount = len(set(helloString)) #=> 7
    

    这是sets进一步阅读的链接

    计数器

    您还可以使用计数器,如果您仍然需要该信息,它还可以告诉您单词的使用频率。

    from collections import Counter
    
    helloString = ['hello', 'world', 'world', 'how', 'are', 'you', 'doing', 'today']
    counter = Counter(helloString)
    len(counter) #=> 7
    counter["world"] #=> 2
    

    循环

    在循环结束时,您可以检查countlen,此外,您将helloString 错误输入为words

    uniqueWordCount = 0
    helloString = ['hello', 'world', 'world', 'how', 'are', 'you', 'doing', 'today']
    count = {}
    for word in helloString:
       if word in count :
          count[word] += 1
       else:
          count[word] = 1
    len(count) #=> 7
    

    【讨论】:

    • 您的循环版本只是复制了集合的功能,因为集合基本上是一个包含被忽略值的字典。
    • @jamylax,是的,但我将它包括在内,以防 OP 想要更详细的一个(这正是我还包括一组的原因)。我将循环示例移到按钮上。
    • 如果您只将值始终设置为True,则count 没有理由成为字典。将其更改为 set
    • @jamylak 我使用了字典,因为 OP 使用了字典。如果他想而不是尝试设置版本,那很好。我更改了答案,以对 OP 的原始代码进行最小的更改。
    • 现在这很有意义,因为您使用的是字典的值
    【解决方案3】:

    您可以使用collections.Counter

    helloString = ['hello', 'world', 'world']
    
    from collections import Counter
    
    c = Counter(helloString)
    
    print("There are {} unique words".format(len(c)))
    print('They are')
    
    for k, v in c.items():
        print(k)
    

    我知道这个问题不是专门要求这个,而是为了维持秩序

    helloString = ['hello', 'world', 'world', 'how', 'are', 'you', 'doing', 'today']
    
    from collections import Counter, OrderedDict
    
    class OrderedCounter(Counter, OrderedDict):
        pass
    
    c = OrderedCounter(helloString)
    
    print("There are {} unique words".format(len(c)))
    print('They are')
    
    for k, v in c.items():
        print(k)
    

    【讨论】:

    • 我不知道,也许有人认为我抄袭了。我没有。但正如你首先回答的那样,这些答案基本上是相同的,我不介意撤回我的答案。
    【解决方案4】:

    在您当前的代码中,您可以在已设置count[word]else 情况下增加uniqueWordCount,或者只是在字典中查找键的数量:len(count)

    如果你只想知道唯一元素的个数,那么获取set中的元素:len(set(helloString))

    【讨论】:

      【解决方案5】:

      我会使用一组来做到这一点。

      def stuff(helloString):
          hello_set = set(helloString)
          return len(hello_set)
      

      【讨论】:

      • 同样的事情和什么?您的意思是与您发布的答案相同,因为我正在写我的,因此无法看到此页面?感谢您指出了这一点。作为记录,我确实赞成你的回答......
      • 以为你说的是​​“而不是使用”。我的错。删除了反对票。
      【解决方案6】:

      计数器是执行此操作的有效方法。 这段代码类似于计数器,

      text = ['hello', 'world']
      
      # create empty dictionary
      freq_dict = {}
       
      # loop through text and count words
      for word in text:
          # set the default value to 0
          freq_dict.setdefault(word, 0)
          # increment the value by 1
          freq_dict[word] += 1
       
      
      
      for key,value in freq_dict.items():
          if value == 1:
               print(f'Word "{key}" has single appearance in the list')
      
      Word "hello" has single appearance in the list
      Word "world" has single appearance in the list
      
      [Program finished]
      

      【讨论】:

        【解决方案7】:

        我可能误读了这个问题,但我相信目标是找到在列表中只出现一次的所有元素。

        from collections import Counter
        helloString = ['hello', 'world', 'world', 'how', 'are', 'you', 'doing', 'today']
        counter = Counter(helloString)
        uniques = [value for value, count in counter.items() if count == 1]
        

        这将为我们提供 6 个项目,因为“世界”在我们的列表中出现了两次:

        >>> uniques
        ['you', 'are', 'doing', 'how', 'today', 'hello']
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-06-21
          • 1970-01-01
          • 1970-01-01
          • 2012-08-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多