Python:在一行文本中最常返回5

时间:2017-09-07 02:02:47

标签: python-3.x dictionary

我正在尝试编写一个函数,该函数将采用一行文本并返回前5个最常用的单词。如果两个相同的单词具有相同的频率,则按字母顺序返回。使用集合中的计数器:

def top5_words(text):
    top5 = {}
    freq = Counter(text.split()).most_common(5)
    for i in freq:
        top5[i[0]] = i[1]
    return sorted(top5.items())[:5]

确实返回[('a', 1), ('one', 3), ('racehorse', 1), ('two', 2), ('was', 2)],但我想通过这个词返回它。示例:['one', 'two', 'was', 'a', 'racehorse']

1 个答案:

答案 0 :(得分:0)

most_common()已按顺序返回项目,因此:

def top5_words(text):
    freq = Counter(text.split()).most_common(5)
    return [word for word, _ in freq]

会做你想做的事。