首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在PHP中索引文本文件

问在PHP中索引文本文件
EN

Stack Overflow用户
提问于 2009-09-03 09:02:58
回答 1查看 2K关注 0票数 0

我被设置了一个挑战,创建一个索引器,接受所有4个字符或更多的单词,并将它们存储在数据库中,以及单词被使用的次数。

我必须在4000个txt文件上运行这个索引器。目前,这大约需要12-15分钟--我想知道是否有人有加快速度的建议?

目前,我将单词放在一个数组中,如下所示:

代码语言:javascript
复制
// ==============================================================
// === Create an index of all the words in the document
// ==============================================================
function index(){
    $this->index = Array();
    $this->index_frequency = Array();

    $this->original_file = str_replace("\r", " ", $this->original_file);
    $this->index = explode(" ", $this->original_file);

    // Build new frequency array
    foreach($this->index as $key=>$value){
        // remove everything except letters
        $value = clean_string($value);

        if($value == '' || strlen($value) < MIN_CHARS){
            continue;
        }

        if(array_key_exists($value, $this->index_frequency)){
            $this->index_frequency[$value] = $this->index_frequency[$value] + 1;
        } else{
            $this->index_frequency[$value] = 1;
        }
    }
    return $this->index_frequency;
}

我认为目前最大的瓶颈是在数据库中存储单词的脚本。它需要将文档添加到essays表中,然后如果表中存在单词,只需将essayid(单词的频率)附加到字段中,如果单词不存在,则添加它……

代码语言:javascript
复制
// ==============================================================
// === Store the word frequencies in the db
// ==============================================================
private function store(){
    $index = $this->index();

    mysql_query("INSERT INTO essays (checksum, title, total_words) VALUES ('{$this->checksum}', '{$this->original_filename}', '{$this->get_total_words()}')") or die(mysql_error());

    $essay_id = mysql_insert_id();

    foreach($this->index_frequency as $key=>$value){

        $check_word = mysql_result(mysql_query("SELECT COUNT(word) FROM `index` WHERE word = '$key' LIMIT 1"), 0);

        $eid_frequency = $essay_id . "(" . $value . ")";

        if($check_word == 0){
            $save = mysql_query("INSERT INTO `index` (word, essays) VALUES ('$key', '$eid_frequency')");
        } else {
            $eid_frequency = "," . $eid_frequency;
            $save = mysql_query("UPDATE `index` SET essays = CONCAT(essays, '$eid_frequency') WHERE word = '$key' LIMIT 1");
        }
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2009-09-03 09:09:02

您可以考虑分析您的应用程序,以确切地了解您的瓶颈所在。这可能会让您更好地了解哪些方面可以改进。

关于数据库优化:检查是否在word列上有索引,然后尝试降低访问数据库的次数。也许是INSERT ... ON DUPLICATE KEY UPDATE ...?

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1372286

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档