如何扭转内容旋转

时间:2016-11-21 14:39:18

标签: php python mysql reverse-engineering

我试图创建一个可以扭转内容旋转的工具。

您可以在下面看到什么是内容旋转:

{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. 蓝色:“他把铅笔砸在桌子上,在他累了的时候嚼着口香糖。”
  3. 问题:

    想象一下,我的数据库中有500个结果,如何将这500个结果反转为像这样做一个旋转句

    {Max | He} {taps | raps | thumps | drums}他的{铅笔|手指} {对| on} {他的| {桌子|桌子|写字台}和{chews |}嚼了一下...哼哼{当|时间} {他是|他是} {无聊|懒惰}。

    感谢你的时间!

1 个答案:

答案 0 :(得分: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
;

返回: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";