我正在尝试从文本文件中查找关键字,当找到关键字时,我为每个匹配项提供 1 分。下面的程序有效地计算分数,但不会将分数从高到低排序。请为我提供此问题的解决方案。
这是代码:
<?php
$lines = file("Abstract.txt");
$Result = array();
$index = 0;
$search_term1= "Tamoxifen";
$search_term2="Doxorubicin";
$search_term3="Synergistic";
$search_term4="MCF-7";
$search_term5="Inhibition";
$keywords = array($search_term1, $search_term2, $search_term3);
$replace_keyword = array("<b>".$search_term1."</b>", "<b>".$search_term2."</b>", "<b>".$search_term3."</b>");
foreach ($lines as $line_num => $line)
{
if($line_num > 1)
{
$arr = explode("\t", $line); //Reads tab separated file
$Pubmed = trim((string)$arr[0]); //first column is Pubmed
$title = trim((string)$arr[1]); //second column is title
$abstract = trim((string)$arr[2]); //third column is abstract
$score = substr_count(strtoupper($title), strtoupper($search_term1)) + substr_count(strtoupper($abstract), strtoupper($search_term1)); //counts occurrence of 1st string in title & abstract
$score += (substr_count(strtoupper($title), strtoupper($search_term2)) + substr_count(strtoupper($abstract), strtoupper($search_term2))); //counts occurrence of 2nd string in title & abstract
$score += (substr_count(strtoupper($title),strtoupper($search_term3)) + substr_count(strtoupper($abstract), strtoupper($search_term3))); //counts occurrence of 3rd string in title & abstract
//store the result as well as data into array
$Result[$index]["Pubmed"] = $Pubmed;
$Result[$index]["<BR>score"] = $score;
$Result[$index]["<BR>title"] = str_ireplace($keywords, $replace_keyword, $title);
$Result[$index]["<BR>abstract"] = str_ireplace($keywords, $replace_keyword, $abstract);
$index++;
}
}
//sort the array by score
$sorter=array();
$ret=array();
reset($Result);
$key = "score";
foreach ($Result as $ii => $va) {
$sorter[$ii]=$va[$key];
}
arsort($sorter);
foreach ($sorter as $ii => $va) {
$ret[$ii]=$Result[$ii];
}
$Result=$ret;
foreach($Result as $instance)
{
$keys = array_keys($instance);
foreach($keys as $key)
{
if(!strcmp($key,"abstract"))
echo "\n<b>".$key."</b> : ".$instance[$key]."\n";
else
echo "<b>".$key."</b> : ".$instance[$key]."\n";
}
echo "\n\n_________________________________________________________________________________________________________________________________________________________________________________________________\n\n";
}
?>