0

我有 CSV 文件,想计算一列 9000 行中的重复单词。

文件的例子
谢谢
好的
好的
谢谢
好的
谢谢

所需的结果将类似于

谢谢=3,好的=1,不错=2。

我找到了以下 PHP 代码,但我无法让它工作,并将 CSV 文件的内容复制到file.txt我做错了什么吗?

<?php
$file = (''C:\Users\wnmb4793\Desktop\Test\file.txt'');

$fh = fopen($file, 'rb');

$tag = array();
while($col = fgetcsv($fh)) {

if (isset($tag[$col[2]])) {
$tag[$col[2]]++;
}
else {
$tag[$col[2]] = 1;
}
?>
4

2 回答 2

1

First problem I can see is:

 $file = (''C:\Users\wnmb4793\Desktop\Test\file.txt'');

Should be

 $file = ('C:\Users\wnmb4793\Desktop\Test\file.txt');

The next step

You need to loop through each word in the file. Something like:

while we are not at the end of the file.
     if( we have seen this word before ) // Think about the isset() method.
         find it's entry and add one to it's value
     else
         add a new entry, and set it's value to 1.
end while

I've given you the pseudo-code. Now turn it into PHP! :)

于 2013-04-11T15:06:26.000 回答
1

只是几个错误。您的代码有效。

$file = 'C:\Users\wnmb4793\Desktop\Test\file.txt';

$fh = fopen($file, 'rb');

$tag = array();
while($col = fgetcsv($fh)) 
{
  $value = $col[0]; // change 0 to column number you need, 0 - first 
  if ( isset($tag[$value]) ) 
    $tag[$value]++;
    else 
    $tag[$value] = 1;
}

print_r($tag);

结果:

Array
(
    [thanks] => 3
    [ok] => 1
    [nice] => 2
)
于 2013-04-11T15:12:23.590 回答