2016-11-21 87 views
1

我正在嘗試創建一個可以反轉內容旋轉的工具。
如何反轉內容旋轉

下面你可以看到什麼內容紡:

{Max|He} {taps|raps|thumps|drums} his {pencil|pen|finger} {against|on} {his|the} {desk|table|writing desk} and {chews|chews on|gnaws on} gum {when|while} {he’s|he is} {bored|tired|lazy}. 

enter image description here

  1. RED:「最大砰砰他的辦公桌上他的手指和膠啃的時候,他是懶。」
  2. 藍色:「他搓着鉛筆靠在桌子上,在他累了的時候嚼着口香糖。」

問題:

可以想象我有500個結果在我的數據庫,我怎樣才能扭轉這種500個結果做出一個旋一句話這樣嗎?

{最大|他} {水龍頭| raps |重擊|鼓}他的{鉛筆|手指} {反對|在} {他的} {桌子|寫字檯}和{嚼|嚼在|咬上}口香糖{when | while} {他是|他是} {無聊|累|懶}。

感謝您的時間!

+0

以及 - 在第一步驟將被創建*所有* 10368次的結果(這是微不足道的),第二個是餵養它們在一個複雜的模式識別算法(這是遠的SO範圍之外) –

回答

1

在PostgreSQL:

create TABLE tbl (c TEXT); 
INSERT INTO tbl(c) 
VALUES ('Max taps his pencil') 
    ,('Max raps his pencil') 
    ,('Max raps his drums') 
    ,('Max raps his drums pencil') 
; 

SELECT nr, ARRAY_AGG(DISTINCT elem) FROM (
    SELECT 
    elem, 
    row_number() 
    OVER (PARTITION BY id) AS nr 
    FROM (SELECT 
      id, 
      regexp_split_to_table(c, ' ') AS elem 
     FROM tbl) x 
) a GROUP BY nr; 

返回:

1,{Max} 
2,{raps,taps} 
3,{his} 
4,{drums,pencil} 
5,{pencil} 

加入結果爲答案

SELECT string_agg(
    CASE WHEN 2 > array_length(w,1) THEN w[1]::TEXT 
            ELSE '{'||array_to_string(w,'|')||'}' 
    END 
    ,' ') FROM (SELECT nr, ARRAY_AGG(DISTINCT elem) as w FROM (
    SELECT 
    elem, 
    row_number() 
    OVER (PARTITION BY id) AS nr 
    FROM (SELECT 
      id, 
      regexp_split_to_table(c, ' ') AS elem 
     FROM tbl) x 
) a GROUP BY nr ORDER BY nr 
) b 
; 

Retuns:Max {raps|taps} his {drums|pencil} pencil

PHP的解決方案:

/*Read this from database*/ 
$in = array('Max taps his pencil' 
    ,'Max raps his pencil' 
    ,'Max raps his drums' 
    ,'Max raps his drums pencil'); 

$statWordsAtIndex = []; 

$addWordAtIndex = function ($word,$index) use (&$statWordsAtIndex) { 
    if (!array_key_exists($index,$statWordsAtIndex)) { 
     $statWordsAtIndex[$index] = [$word]; 
    } 
    else if (!in_array($word,$statWordsAtIndex[$index])) { 
     $statWordsAtIndex[$index][] = $word; 
    } 
}; 
foreach ($in as $sid => $sentence) { 
    $words = explode(' ',$sentence); 
    foreach ($words as $pos => $word) { 
     $addWordAtIndex($word,$pos); 
    } 
} 
foreach ($statWordsAtIndex as $words) { 
    if (2 > count($words)) { 
     echo $words[0],' '; 
    } 
    else { 
     echo '{',implode('|',$words),'} '; 
    } 
} 
echo "\n"; 
+0

謝謝的爲你的答案。我的情況內容更長,旋轉結果內容300字。我不確定在這種情況下工作。 – Pixel

+0

@像素字數沒有限制,php解決方案會更適合你嗎? – cske

+0

不,我不受語言,postgresql,python,php的限制。 – Pixel