[我想从php上传文件中计算重复的单词

问题描述 投票:0回答:1

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

php file-handling
1个回答
0
投票

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

// Get the contents of the file
$contents = file_get_contents('my_file.txt');
// 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) {
    // 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
    if ($occurrences[$word] > 1) {
        $duplicates[] = $word;
    }
}

// Output the duplicates in a comma separated format
echo "Duplicates in file: " . join(", ", $duplicates);
© www.soinside.com 2019 - 2024. All rights reserved.