当前位置: 面试刷题>> 词频统计 (经典算法题500道)


题目描述补充

题目:词频统计

给定一个字符串(可能包含标点符号、空格等),请编写一个程序来统计并输出该字符串中每个单词(忽略大小写,标点符号视为单词的分隔符)出现的频率,并按照频率从高到低排序(如果频率相同,则按字典序升序排序)。

示例输入

"Hello, world! Welcome to the world of coding. Enjoy coding, everyone!"

期望输出

the: 2
world: 2
coding: 2
Hello: 1
Welcome: 1
of: 1
to: 1
Enjoy: 1
everyone: 1

PHP 示例代码

<?php
function wordFrequency($str) {
    // 使用正则表达式替换标点符号并转为小写
    $words = preg_replace('/[^\w\s]+/', ' ', strtolower($str));
    // 分割字符串为单词数组
    $words = explode(' ', $words);
    // 使用关联数组统计词频
    $frequency = array();
    foreach ($words as $word) {
        if (!empty($word)) {
            if (!isset($frequency[$word])) {
                $frequency[$word] = 0;
            }
            $frequency[$word]++;
        }
    }
    // 按频率降序,频率相同则按字典序升序排序
    arsort($frequency);
    // 输出结果
    foreach ($frequency as $word => $count) {
        echo "$word: $count\n";
    }
}

// 示例输入
$input = "Hello, world! Welcome to the world of coding. Enjoy coding, everyone!";
wordFrequency($input);

// 码小课网站中有更多相关内容分享给大家学习
?>

Python 示例代码

def word_frequency(s):
    # 使用正则表达式替换标点符号并转为小写
    import re
    words = re.sub(r'[^\w\s]', ' ', s.lower()).split()
    # 使用字典统计词频
    frequency = {}
    for word in words:
        if word:
            if word not in frequency:
                frequency[word] = 0
            frequency[word] += 1
    # 按频率降序,频率相同则按字典序升序排序
    sorted_words = sorted(frequency.items(), key=lambda x: (-x[1], x[0]))
    # 输出结果
    for word, count in sorted_words:
        print(f"{word}: {count}")

# 示例输入
input_str = "Hello, world! Welcome to the world of coding. Enjoy coding, everyone!"
word_frequency(input_str)

# 码小课网站中有更多相关内容分享给大家学习

JavaScript 示例代码

function wordFrequency(str) {
    // 使用正则表达式替换标点符号并转为小写
    const words = str.toLowerCase().replace(/[^\w\s]/g, ' ').split(/\s+/).filter(Boolean);
    // 使用Map统计词频
    const frequency = new Map();
    for (const word of words) {
        frequency.set(word, (frequency.get(word) || 0) + 1);
    }
    // 将Map转换为数组,并按频率降序,频率相同则按字典序升序排序
    const sortedWords = Array.from(frequency.entries()).sort((a, b) => {
        if (a[1] === b[1]) {
            return a[0].localeCompare(b[0]);
        }
        return b[1] - a[1];
    });
    // 输出结果
    sortedWords.forEach(([word, count]) => {
        console.log(`${word}: ${count}`);
    });
}

// 示例输入
const input = "Hello, world! Welcome to the world of coding. Enjoy coding, everyone!";
wordFrequency(input);

// 码小课网站中有更多相关内容分享给大家学习

这些示例代码分别用 PHP、Python 和 JavaScript 实现了词频统计的功能,并按照题目要求进行了排序和输出。

推荐面试题