私はPHPを使用しています。
5 つの文字列があるとします。
"The quick brown fox"
"The sly brown fox"
"The sly brown chicken"
"Totally different text here"
"Not like the others"
そして、残りと最も「異なる」2つを見つけたいと思います。それを 1000 個のテキスト文字列に拡張して、たとえば 300 個の最も「異なる」文字列を取得できるようにしたいと考えています。
どこから始めればよいですか?
編集
「異なる」をどのように定義するかは議論の余地があります!
*編集2 *
similar_text
PHPの機能に応じて、「異なる」を異なると定義しました。しかし、他の定義があるかもしれません。本当の問題は、すべてのテキスト文字列を比較する方法です。Jean は、合計を数えることを提案しました。これは、そうする Phillipe のコードのハッキングされたバージョンです。
$strings = array(
"The quick brown fox",
"The sly brown fox",
"The sly brown chicken",
"Totally different text here",
"Not like the others"
);
$n = 3;
$sim = array();
for ($i = 0; $i < count($strings); $i++) {
$total = 0;
for ($j = 0; $j < count($strings); $j++) {
if($strings[$i] != $strings[$j]) {
$sim_val = similar_text($strings[$i], $strings[$j]);
$total += $sim_val;
$sim[$strings[$i]][] = array(
"sim" => $sim_val,
"w1" => $strings[$i],
"w2" => $strings[$j]
);
}
}
$sim[$strings[$i]]['total'] = $total;
}
uasort($sim, function($w1, $w2) {
return $w1["total"] > $w2["total"];
});
$sim = array_keys($sim);
$sim = array_slice($sim,0,$n);
それが返ってくる
Array
(
[0] => Not like the others
[1] => Totally different text here
[2] => The quick brown fox
)
これは正しい答えのようです。すべてに感謝します(質問に反対票を投じた人は別として。あなたにブーイングします;-)
編集 3 *
わかりましたので、これを 1000 個の文字列でテストしてきました。それぞれに約 500 の一意の単語があり、strlen
約 14000 の単語があります。したがって、... これをすばやく実行するにはsimilar_text
、指摘したように遅いので、すぐに忘れることができます。簡単な「compare_words」関数を書きました。
function same_words($text1,$text2) {
$words_1 = array_unique(explode(" ",$text1));
$words_2 = array_flip(array_unique(explode(" ",$text2)));
foreach($words_1 AS $word) {
if($words_2[$word]) {
$count++;
}
}
return $count;
}
しかし、それも遅すぎます。