我想从php上传的文件中计算重复的单词,我如何得到它

我想计算PHP中已上传文件中的重复单词,如何执行此任务?

LB101355 回答:我想从php上传的文件中计算重复的单词,我如何得到它

假设我们正在处理文本文件,这是一个相对简单的任务:

<?php

// Get the contents of the file
$contents = "Duplicate duplicate duplicate three times three is twenty six thousand three hundred and fifty one. There are fifty nine people in the universe. Times that by nine and divide it by three,then negate a million and you can calculate the IQ of donald trump. This is pure waffle and I can repeat this nine times but shall restrain and instead talk like ollie and use big words and sound very cool. Funny thing is I've typed n instead of and so many times because it's a habit n I like eating rabbit meat as it is very succulent and juicy. Duplicate words shall be found!";
// Split the contents into an array of individual words
$words = explode(' ',$contents);
// Define arrays to track occurrences and duplicates
$occurrences = [];
$duplicates = [];

// Iterate through each word in the sample
foreach ($words as $word) {
    // Convert word to lower case (case-insensitivity)
    $word = strtolower($word);

    // Increment the current occurrence count of current word
    $occurrences[$word] = isset($occurrences[$word]) ? $occurrences[$word] + 1 : 1;

    // If the word has occurred more than once,add it to our duplicates
    // Remove the in_array call if you wish to count each instance of a duplicated word instead of once per duplicate
    if ($occurrences[$word] > 1 && !in_array($word,$duplicates)) {
        $duplicates[] = $word;
    }
}

// Output the duplicates in a comma separated format
echo "Duplicates in file: " . join(",",$duplicates);
本文链接:https://www.f2er.com/3050341.html

大家都在问