需要逻辑建议来编码此 PHP 练习


need advice with logic for coding out this php exercise

我在文本文件中有一个列表,其中包含英语中使用的前 1000 个单词。每行有一个最多 50 个单词的列表,如下所示:

的,东西,

是,东西,嗨,再见,你好,a,东西
酷,免费,真棒,祈祷,是,犯罪
等。

我需要使用该文件作为输入编写代码,以制作一个输出文件,其中包含至少五十个不同列表中的单词对列表。例如,在上面的例子中,THE & IS一起出现两次,但每隔一对只出现一次。

我无法存储所有可能的单词对,所以没有蛮力。

我正在尝试学习语言,但我被困在这本书的这个练习上。请帮忙。这方面的任何逻辑、指导或代码都会对我有所帮助。

这就是我目前所拥有的。它没有做预期的事情,但我被卡住了:

法典:

//open the file
$handle = fopen("list.txt", 'r');
$count = 0;
$is = 0;
while(!feof($handle)) {
    $line = fgets($handle); 
    $words = explode(',', $line);
    echo $count . "<br /><br />";
    print_r($words);
    foreach ($words as $word) {
        if ($word == "is") {
            $is++;
        }
    }
    echo "<br /><br />";
$count++;
}
echo "Is count: $is";
//close the file
fclose($handle);
$fp = fopen('output.txt', 'w');
fwrite($fp, "is count: " . $is);
fclose($fp);

这就是我想出的,但我认为它太臃肿了:

计划:
检查$words数组
的第一个值将值存储到$cur_word
$cur_word作为键存储在数组中 ($compare ) 和
将计数器(行号)存储为该键
的值此时
将是 1查看$cur_word是否在每行上,如果是,则
将值放入$compare中,键作为$cur_word 如果数组至少有 50 个值,则继续
否则转到$words数组
的下一个值如果它有 50 个值,则
转到下一个值并执行相同的操作
比较两个列表以查看匹配
的值数如果至少为 50,则附加
输出文件中的单词

对每个单词重复此过程

这个问题可能有100种解决方案。 这是一个

$contents = file_get_contents("list.txt");
//assuming all words are separated by a , and converting new lines to word separators as well
$all_words = explode(",", str_replace("'n", ",", $contents)); 
$unique_words = array();    
foreach ($all_words as $word) {
    $unique_words[$word] = $word;
}

这将在数组中为您提供文件中的所有唯一单词。

您也可以使用相同的技术来计算单词

$word_counts = array();
foreach ($all_words as $word) {
    if (array_key_exists($word, $word_counts)) {
        $word_counts[$word]++;
    } else {
        $word_counts[$word] = 1;
    }
}

然后,您可以循环并保存结果

$fp = fopen("output.txt", "w");
foreach ($word_counts as $word => $count) {
    fwrite($fp, $word . " occured " . $count . " times" . PHP_EOL);
}
fclose($fp);