在php中,如何在glob函数的foreach循环中将文本文件的内容作为值获取?
我正在开发一个带有向量空间模型的搜索引擎。我成功地使用代码中已经定义的关联数组数据计算了tf idf。现在,我希望数据应该来自我有一个文件夹的目录,在每个文件夹中都有一些带有虚拟数据的文本文件。我已经尝试了很多,但是在使用glob函数时,我坚持了1点,因为我希望在glob函数的每个循环中,所有.txt文件都是键,其内容是值。。。。下面是我的代码 Tf idf与关联数组数据在php中,如何在glob函数的foreach循环中将文本文件的内容作为值获取?,php,loops,foreach,Php,Loops,Foreach,我正在开发一个带有向量空间模型的搜索引擎。我成功地使用代码中已经定义的关联数组数据计算了tf idf。现在,我希望数据应该来自我有一个文件夹的目录,在每个文件夹中都有一些带有虚拟数据的文本文件。我已经尝试了很多,但是在使用glob函数时,我坚持了1点,因为我希望在glob函数的每个循环中,所有.txt文件都是键,其内容是值。。。。下面是我的代码 Tf idf与关联数组数据 $collection = array( 1 => 'this string is a short string bu
$collection = array(
1 => 'this string is a short string but a good string',
2 => 'this one isn\'t quite like the rest but is here',
3 => 'this is a different short string that\' not as short'
);
$dictionary = array();
$docCount = array();
foreach($collection as $docID => $doc) {
$terms = explode(' ', $doc);
$docCount[$docID] = count($terms);
foreach($terms as $term) {
if(!isset($dictionary[$term])) {
$dictionary[$term] = array('df' => 0, 'postings' => array());
}
if(!isset($dictionary[$term]['postings'][$docID])) {
$dictionary[$term]['df']++;
$dictionary[$term]['postings'][$docID] = array('tf' => 0);
}
$dictionary[$term]['postings'][$docID]['tf']++;
}
}
$temp = ('docCount' => $docCount, 'dictionary' => $dictionary);
正如您在第一个foreach循环中所看到的,$DocID是关键,$doc是集合数组的内容(值)。但我不知道如何在从目录中读取文件时实现完全相同的功能。请参见下面的代码
Tf idf,包含从目录读取的.txt文件及其内容
foreach (glob("C:\\wamp\\www\\Web-info\\documents\\awd_1990_00\\*.txt") as $file) {
$file_handle = fopen($file, "r");
//echo $file;
$dictionary = array();
$docCount = array();
foreach($file as $docID=> $value) {
echo $value;
$terms = explode(' ', $doc);
$docCount[$docID] = count($terms);
foreach($terms as $term) {
if(!isset($dictionary[$term])) {
$dictionary[$term] = array('df' => 0, 'postings' => array());
}
if(!isset($dictionary[$term]['postings'][$docID])) {
$dictionary[$term]['df']++;
$dictionary[$term]['postings'][$docID] = array('tf' => 0);
}
$dictionary[$term]['postings'][$docID]['tf']++;
}
}
}
$temp = array('docCount' => $docCount, 'dictionary' => $dictionary);
这会在第一个foreach循环中出现错误,该错误为foreach循环提供了无效的arugument。如前所述,我希望.txt文件作为键,其内容作为值,在第一个foreach循环中。但是我犯了这个错误谁能告诉我怎么做。。提前感谢。如果要将整个文件视为一个值,可以使用
file\u get\u contents()
将文件读入字符串:
$dictionary = array();
$docCount = array();
foreach (glob("C:\\wamp\\www\\Web-info\\documents\\awd_1990_00\\*.txt") as $docID) {
$value = file_get_contents($docID);
...
}
我不明白你想干什么
$file
只是一个文件名,在foreach
中循环什么?如果要在这些行上循环,请使用while($line=fgets($file\u handle)
@Barmar感谢您的回复。我正在尝试在第一个foreach循环中将文件名作为键,其内容作为值作为我的要求,而不需要另一个while循环来获取其内容。所有内容都应该在glob函数中。是否可能?谢谢@Barmar现在我将文件内容作为值获取,但仍然有一个问题是t我希望文件名作为键而不是数字([0]、[1]、[2]等…)我希望这样([1.txt]=>其内容,[2.txt]=>其内容等)。非常感谢您的回复。您不能在数组中重复相同的键。文件中的所有行都具有相同的文件名。我希望获得一个包含其内容数组的文档数组(){[1]contnet of document,[2]第二份文件的内容……。}请更新问题并显示您试图获取的内容。它不是很清楚。在您说您不需要数字键之前,现在看起来您需要数字键。感谢您的回答。您更新的代码没有生成文件数组及其内容,并且给出了与foreach循环提供的无效参数相同的错误。我需要doument数组其内容如[1]=>第一份文件的内容[2]=>第二份文件的内容等。请帮助我。谢谢。