Skip to main content
 首页 » 编程设计

python之查找第 n 个最常见的单词并在 python 中计数

2025年05月04日9lexus

我是一名新来的本科生,热爱编程。实践中遇到问题,想在这里求助。

给一个字符串一个整数 n,返回第 n 个最常见的单词及其计数,忽略大小写。

对于单词,返回时确保所有字母都是小写!

提示:split() 函数和字典可能会有用。

示例:

输入:“apple apple apple blue Blue call”, 2

输出:列表 ["blue", 2]

我的代码如下:

from collections import Counter 
def nth_most(str_in, n): 
    split_it = str_in.split(" ") 
    array = [] 
    for word, count in Counter(split_it).most_common(n): 
        list = [word, count] 
        array.append(count) 
        array.sort() 
        if len(array) - n <= len(array) - 1: 
            c = array[len(array) - n] 
            return [word, c] 

测试结果如下:

Traceback (most recent call last): 
  File "/grade/run/test.py", line 10, in test_one 
    self.assertEqual(nth_most('apple apple apple blue blue call', 3), ['call', 1]) 
  File "/grade/run/bin/nth_most.py", line 10, in nth_most 
    c = array[len(array) - n] 
IndexError: list index out of range 

还有

Traceback (most recent call last): 
  File "/grade/run/test.py", line 20, in test_negative 
    self.assertEqual(nth_most('awe Awe AWE BLUE BLUE call', 1), ['awe', 3]) 
AssertionError: Lists differ: ['BLUE', 2] != ['awe', 3] 
 
First differing element 0: 
'BLUE' 
'awe' 

我不知道我的代码有什么问题。

非常感谢您的帮助!

请您参考如下方法:

由于您正在使用 Counter,请明智地使用它:

import collections 
 
def nth_most(str_in, n): 
    c = sorted(collections.Counter(w.lower() for w in str_in.split()).items(),key = lambda x:x[1]) 
    return(list(c[-n])) # convert to list as it seems to be the expected output 
 
print(nth_most("apple apple apple blue BlUe call",2))  

构建词频字典,根据值(元组的第 2 个元素)对项目进行排序,并选择倒数第 n 个元素。

这会打印 ['blue', 2]。

如果第一或第二位置有两个相同频率(并列)的单词怎么办?此解决方案不起作用。相反,对出现的次数进行排序,提取第 n 个最常见的出现,然后再次运行计数器字典以提取匹配项。

def nth_most(str_in, n): 
    c = collections.Counter(w.lower() for w in str_in.split()) 
    nth_occs = sorted(c.values())[-n] 
    return [[k,v] for k,v in c.items() if v==nth_occs] 
 
print(nth_most("apple apple apple call blue BlUe call woot",2)) 

这次它打印:

[['call', 2], ['blue', 2]]