drduinfu915094 2014-01-17 11:12
浏览 21

如何在文本开头找到短语(单词)

How find phrase (words) at beginning of text

I need very fast solution for find out if text begins some of known phrases

Phrases I have in Mysql (innodb) table like this:

CREATE TABLE IF NOT EXISTS `phrase` (
  `id` int(10) unsigned NOT NULL,
  `text` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `text` (`text`)
) ENGINE=InnoDB;

INSERT INTO phrase VALUES (1, 'one');
INSERT INTO phrase VALUES (2, 'one two');
INSERT INTO phrase VALUES (3, 'two');
INSERT INTO phrase VALUES (4, 'three');

Phrase text is ONE OR MULTIPLE WORDS. Table contains about 20.000 rows

Now I get text from user request and need to know if this text begins like any phrase. But I need find out longest phrase in database

I should precache rows to server memory or I can search in mysql table.

I tryed this

 $_REQUEST['text'] = 'one two three';
 $_REQUEST['text'] = explode(' ', $_REQUEST['text']);
 $search = ''; $found = null;
 foreach ($_REQUEST['text'] as $next_word) {
  $search .= (($search == '') ? '' : ' ').$next_word;
  $query = "SELECT SQL_CACHE * FROM phrase WHERE phrase = '{$search}' LIMIT 1;";
  ...
  $row = mysql_fetch_assoc($result);
  if ( ... not found ... ) break;
   else $found = $row;
 }
 print_r($row); // print latest found phrase "one two"

I thing that this way is slowly, because I need FULL TABLE SCAN for EACH WORD

Do you know an faster solution?

  • 写回答

3条回答 默认 最新

  • duan36000 2014-01-17 11:15
    关注

    instead

    $query = "SELECT SQL_CACHE * FROM phrase WHERE phrase = '{$search}' LIMIT 1";
    

    you can do liket this:

    $query = "SELECT SQL_CACHE * FROM phrase WHERE phrase like '%{$search}%' LIMIT 1";
    

    Or additionally you can reduce you code like this:

    $count = count($_REQUEST['text']);
    $where = "";
    for($loop=0;$count<$loop;$loop++) {
    if($loop!=($count-1))
     $where .= "phrase like '%".$_REQUEST['text'][$loop]."%' OR";
    else 
     $where .= "phrase like '%".$_REQUEST['text'][$loop]."%'";
    }
    $query = "SELECT SQL_CACHE * FROM phrase WHERE $where LIMIT 1;";
    
    评论

报告相同问题?

悬赏问题

  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口