返回最频繁单词的函数

2024-04-19 07:10:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我想要编写返回最频繁单词的函数,具体要求如下:

  • 显示8个最常用的单词
  • 单词长度必须超过4个符号
  • 消除停止词
  • 跳过点和逗号

我写了一个简短的函数,但我不知道如何将需求与我的函数联系起来:

  • 停止说话
  • 单词长度必须超过4个符号

例如

txt=''Python于1991年首次发布。它是一种解释性的高级通用编程语言。它是面向对象的

由Guido van Rossum设计的Python实际上有一种以代码可读性为中心的设计理念。Python社区将根据代码的Pythonic程度对彼此的代码进行分级。 Python的库允许程序员快速入门。他们很少需要从头开始。如果一个程序员想跳进机器学习领域,那么有一个库可以供他使用。如果他们想创建一个漂亮的图表,有一个库。如果他们希望在CLI中显示进度条,那么有一个用于此的库

一般来说,Python是编程语言的乐高积木;找到一个盒子,上面有使用说明,然后开始工作。没有什么需要从头开始的。”

停止词=[“a”、“to”、“if”、“it”、“cross”、“after”、“after”、“reach”、“against”、“all”、“几乎”、“sole”]

from collections import Counter

def words_counter(sample_txt):
    return Counter(sample_txt.lower().split()).most_common(8)
words_counter(txt)

[('a', 9),
 ('to', 8),
 ('python', 4),
 ('is', 4),
 ('the', 4),
 ('it', 3),
 ('code', 3),
 ('they', 3),
 ('if', 3),
 ('there’s', 3)]

Tags: tosample函数代码txtifcounter符号
2条回答

一种方法是首先创建一个新的单词列表,删除所有与这两个条件不匹配的单词,然后从该列表中构建Counter

顺便说一下,您的代码忽略了跳过点和逗号的要求

import re
from collections import Counter

def common_words(text, stop_words, min_length):
    # requirement 1: get rid of dot and comma
    clean_text = re.sub(r'[.,]', '', text)

    # requirement 2: create list of words that are longer than min_length characters and not in stop_words
    words = [ word for word in clean_text.lower().split() if len(word) > min_length and word not in stop_words ]

    # now count like you did before:
    return Counter(words).most_common(8)
    

您可以尝试使用一个generatorwalrus operator,如下所示(对于python 3.8+):

def words_counter(sample_txt):
    filtered_words = (cleaned for word in sample_txt.split() 
        if (cleaned := word.strip('.,').lower()) not in stop_words
        and len(cleaned) > 4)
    return Counter(filtered_words).most_common(8)

>>> words_counter(txt)
[('python', 4),
 ('there’s', 3),
 ('library', 3),
 ('programming', 2),
 ('programmer', 2),
 ('started', 2),
 ('scratch', 2),
 ('first', 1)]

或者有少量的generatorsaka lazy looping

def words_counter(sample_txt):
    without_dot_comma = (word.strip('.,') for word in sample_txt.split())
    longer_than_4 = (word.lower() for word in without_dot_comma if len(word) > 4)
    without_stop_words = (word for word in longer_than_4 if word not in stop_words)
    return Counter(without_stop_words).most_common(8)

>>> words_counter(txt)
[('python', 4),
 ('there’s', 3),
 ('library', 3),
 ('programming', 2),
 ('programmer', 2),
 ('started', 2),
 ('scratch', 2),
 ('first', 1)]

编辑: 将函数中的最后一行更改为:

return [(v, k) for k, v in Counter(filtered_words).most_common(8)]

相关问题 更多 >