2

これらの文字列の間で最も一般的な単語を使用して、複数の文字列から新しい文字列を作成しようとしています。例えば:

$string[0] = 'Apple iPhone 4S 16GB Locked to Orange';
$string[1] = 'iPhone 4S 16GB boxed new';
$string[2] = 'iPhone 4S 16GB unlocked brand new';
$string[3] = 'Apple iPhone 16GB 4S Special Offer';
$string[4] = 'Apple iPhone 4S Sim Free';

## The new string should be:

$new_string = 'Apple iPhone 4S 16GB';

何百もの元の文字列、または2つだけの文字列が存在する可能性があります...

どこから始めればいいのかわからないので、助けていただければ幸いです。

4

4 に答える 4

2

あなたが試すことができます

$string = array();
$string[0] = 'Apple iPhone 4S 16GB Locked to Orange';
$string[1] = 'iPhone 4S 16GB boxed new';
$string[2] = 'iPhone 4S 16GB unlocked brand new';
$string[3] = 'Apple iPhone 16GB 4S Special Offer';
$string[4] = 'Apple iPhone 4S Sim Free';

print(getCommon($string));

出力

Apple iPhone 4S 16GB

使用する機能

function getCommon($array,$occurance = 3)
{
    $array = array_reduce($array, function($a,$b) { $a = array_merge($a,explode(" ", $b)); return $a; },array());
    return implode(" ",array_keys(array_filter(array_count_values($array),function($var)use($occurance) {return $var > $occurance ;})));
}

ライブデモを見る

于 2012-10-13T19:38:46.297 に答える
1

それを行う別の方法

$min_times_present = 3;
$words  = array();
foreach ($string as $str) {
  $words_string = preg_split('/\s+/', $str, 0, PREG_SPLIT_NO_EMPTY);
  foreach ($words_string as $word) {
    $words[$word] = (isset($words[$word])) ? $words[$word]+1 : 1;
  }
}
$result_arr = array_filter($words, function($value) use ($min_times_present) {
  return ($value >= $min_times_present);
});
arsort($result_arr, SORT_NUMERIC);
$result_str = implode(' ', array_keys($result_arr));
于 2012-10-13T20:05:48.510 に答える
1

次のようなものから始める必要があります。

function getWordCount($someArray)
{
    $wordList = array();
    foreach($someArray as $item) {
        $wordList = array_merge($wordList, explode(' ', $item));
    }

    $result = array_count_values($wordList);
    arsort($result);

    return $result;
}

.スペース文字に基づいて爆発することに注意してください。これは、またはのような句読点などを考慮しません,。これを考慮したい場合は、単純な正規表現パターンを使用して、要件に従って文字列内の単語を取得する必要があります。

デモ: http://codepad.viper-7.com/IuAc2s

于 2012-10-13T19:37:37.437 に答える
0

同様の問題があり、私の解決策は、すべてのフレーズを 1 つの単語配列にマージしてから、出現回数が最も多い単語を取得することでした。

$string = array();
$string[0] = 'Apple iPhone 4S 16GB Locked to Orange';
$string[1] = 'iPhone 4S 16GB boxed new';
$string[2] = 'iPhone 4S 16GB unlocked brand new';
$string[3] = 'Apple iPhone 16GB 4S Special Offer';
$string[4] = 'Apple iPhone 4S Sim Free';
$words=array();
for($i=0;$i<count($string);$i++){
    $words = array_merge($words,str_word_count($string[$i],1));
}

$instances = array_count_values($words);
arsort($instances);
$instances = array_slice($instances,0,5);
foreach($instances as $word=>$count){
    echo $word.' ';
}
    // Outputs "iPhone S GB Apple new"

この方法の問題点は、単語が同じ文字列に複数回出現すると、出現回数が増えることです。

于 2013-11-28T01:34:42.310 に答える