PHP实现文本文件中用户发言单词数统计的需求及代码优化
需求说明
文本文件内是带用户标签的对话内容,示例如下:
<Amanda> Hi there, how are you? <Jack> Hi, im fine ... <Jack> see you later
需要排除<Amanda>、<Jack>这类用户标签,统计每位用户的发言单词数,结果存入对应变量,输出格式示例:
Amanda: 50 Jack: 40
现有代码问题
以下是编写的代码,需要得到正确的实现方案:
$usercount1 = 0; $usercount2 = 0; //Opens a file in read mode $file = fopen("logfile.txt", "r"); //Gets each line till end of file is reached while (($line = fgets($file)) !== false) { //Splits each line into words $words = explode(" ", $line); $words = explode("<Amanda>", $line); //Counts each word $usercount1 = $usercount1 + count($words); } while (($line = fgets($file)) !== false) { //Splits each line into words $words = explode(" ", $line); //Counts each word $usercount2 = $usercount2 + count($words); }
正确实现方案
原代码存在几个核心问题:第一次循环读完文件后,文件指针已到末尾,第二次循环不会执行;用explode分割的方式无法正确提取发言内容,且统计逻辑错误;硬编码用户标签导致扩展性差。
以下是优化后的实现代码:
// 用关联数组存储每个用户的单词数,支持任意用户 $userWordCounts = []; // 打开文件,增加异常判断 $file = fopen("logfile.txt", "r"); if (!$file) { die("无法打开目标文件"); } // 逐行处理对话内容 while (($line = fgets($file)) !== false) { // 去除行首尾空白,跳过空行 $line = trim($line); if (empty($line)) continue; // 用正则匹配提取用户名和发言内容 if (preg_match('/^<([^>]+)>\s*(.*)$/', $line, $matches)) { $username = $matches[1]; $content = $matches[2]; // 清洗内容:去除标点,按空白分割后过滤空元素,统计有效单词数 $cleanContent = preg_replace('/[^a-zA-Z0-9\s]/', ' ', $content); $words = array_filter(explode(' ', trim($cleanContent))); $wordCount = count($words); // 更新对应用户的单词统计 if (!isset($userWordCounts[$username])) { $userWordCounts[$username] = 0; } $userWordCounts[$username] += $wordCount; } } fclose($file); // 按要求格式输出结果 foreach ($userWordCounts as $user => $count) { echo "$user: $count\n"; }
代码说明
- 用正则
/^<([^>]+)>\s*(.*)$/精准提取<>内的用户名和后续发言内容 - 对发言内容做清洗处理,过滤标点和无效空白,确保单词统计准确
- 关联数组存储统计结果,无需提前硬编码用户,支持任意数量的对话用户
- 增加文件打开失败的判断,提升代码健壮性
内容的提问来源于stack exchange,提问作者Unkown Kid
相关产品推荐
相关产品推荐

