如何计算列中的相似单词

时间:2013-04-11 15:02:14

标签: php csv

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

  

文件的例子
  谢谢你   好的   不错的   谢谢你   不错的   谢谢你   

所需的结果类似于

  

thanks = 3,ok = 1,nice = 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;
}
?>

2 个答案:

答案 0 :(得分:1)

我能看到的第一个问题是:

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

应该是

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

下一步

您需要遍历文件中的每个单词。类似的东西:

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

我已经给你伪代码了。现在把它变成PHP! :)

答案 1 :(得分: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
)