2013-04-11 9 views
0

我有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; 
} 
?> 
+1

说实话,它可能是更容易只是CSV导入到数据库中,然后使用SQL向你展示所有的话+多少次。 – Nick 2013-04-11 15:04:20

+1

当您尝试运行代码时会发生什么? – 2013-04-11 15:06:55

+0

从您的评论:'$ value = $ col [2]; //将2更改为需要的列号 - 显然,您需要选择正确的列。 AndreyVolk有正确的答案。 – 2013-04-11 15:32:29

回答

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 
) 
+1

使用$ value = $ col [0];对于第一列 – 2013-04-11 15:26:22

+1

你的情况与一列的文件应该是$ col [0]而不是$ col [2] – 2013-04-11 15:31:54

+0

与fgetcsv并不重要。使用csv,但不要忘记设置$ col [列号] – 2013-04-11 15:39:39

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! :)

+0

原来的海报提供了工作代码,他只是错过了一个简单的细节。伪代码在这里没有帮助。 – 2013-04-11 15:36:41

+1

同意,但OP也提到他们刚刚复制和粘贴。如果OP忽略它,至少他们可以理解它背后的方法,但是这并不严格地回答这个问题,所以你是对的:) – christopher 2013-04-11 15:39:58

相关问题