[英]Replacing words with their synonyms in string
這是即時通訊試圖做的一個非常基本的例子。
我有這個字符串。
$text = 'stackoverflow is intelligent';
刪除停用詞后
$stopwords=array(
'is',
'the',
);
$text = preg_replace($stopwords, "", $text);`
輸出:
stackoverflow智能
用空格將字符串分解后
$text = explode(" ", $text);
輸出數組:
智能堆棧溢出
現在我有兩個字
$text[0]; // stackoverflow
$text[1]; // intelligent
在我的sql數據庫中,我有3個列。 第一個是單詞,第二個是她的同義詞,第三個是字符的最短同義詞。 像這樣:
word synonym shortsynonym
intelligent clever smart
這是問題的難點:
第一步是檢查字符串中的words
在數據庫中是否具有同義詞,在這種情況下,我們必須檢查
$text[0]; // stackoverflow
$text[1]; // intelligent
在檢查完兩者之后,我們得出$text[0]; // stackoverflow
$text[0]; // stackoverflow
主體具有同義詞,因此我們保持不變。 和$text[1]; // intelligent
的結果$text[1]; // intelligent
$text[1]; // intelligent
結果為正。
檢查后,我想執行數據庫搜索和replace
在這種情況下,字intelligent
與她的代名詞,而if
該word
有一個shortest synonym
與更換shortest
, if
這個詞dosent有一個同義詞保留原樣。
possibility1: output: 'stackoverflow is smart'
possibility2: output: 'stackoverflow is clever'
possibility3: output: 'stackoverflow is intelligent'
在這種情況下,返回后的輸出將是:
output: `stackoverflow is smart`
(也許這不是在這里問的真正問題,但是您的任何幫助將不勝感激。對於我的英語不好對不起)
經過檢查后,我想在數據庫中進行搜索,在這種情況下,將smart替換為她的同義詞,如果該單詞具有最短的同義詞,則替換為最短,如果適量單詞的同義詞保持原樣。
根據上面提供的邏輯,適當的SQL將是:
$sql = "SELECT
`word`,
IF(NOT ISNULL(`shortsynonym`), `shortsynonym`, IFNULL(`synonym`, `word`)) as replacement
FROM words
WHERE `word` IN ('stackoverflow', 'intelligent')";
尚未測試過,但是以上內容應該可以幫助您...
程序的設計或編寫查詢的實際機制有問題嗎?
如果是設計,則可能會考慮“同義詞庫”的大小(如果較小),則在程序開始時查詢數據庫並將結果加載到鍵值數組中可能更有意義。 然后,您可以使用數組,而不必在每次請求時都擊中數據庫。 它也應該加快程序的速度。
如果問題出在編寫sql查詢上,則您可能希望花些時間在項目上閱讀一些教程。 我建議為您的查詢使用PDO PHP 5.4,如果您了解它,它會使編寫查詢變得很困難。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.