0

ファイル内で相互参照される文字列内の各単語を使用したいと考えています。

したがって、文字列が与えられた場合:Jumping jacks wake me up in the morning.

  1. 正規表現を使用してピリオドを取り除きます。また、文字列全体が小文字になります。
  2. 次に、PHP の気の利いた関数を使用して、単語を配列に分割しexplode()ます。
  3. 今、残っているのは、文字列で使用されている単語の配列です。

そこから、配列内の各値を調べて値を取得し、それを現在の合計に追加する必要があります。for()ループです。さて、ここで行き詰まります...

リスト ( $wordlist) は次のように構成されています。

wake#4 waking#3 0.125

morning#2 -0.125

\t単語と数字の間に sがあります。値ごとに複数の単語が存在する場合があります。

ここで PHP に必要なことは、配列内の各単語の数値を検索し、その対応する数値をプルして現在の合計に追加することです。これについて私が行く最善の方法は何ですか?

答えは簡単です。単語リストで文字列の場所を見つけてから、タブを見つけて、そこから int を読み取るだけです...いくつかのガイダンスが必要です。

前もって感謝します。

編集:明確にするために-単語リストの値の合計は必要ありません。むしろ、文の単語に対応する個々の値を調べてから、リストでそれらを調べて、それらの値だけを追加します。それらのすべてではありません。

4

2 に答える 2

1

コメントと質問の編集に基づいて回答を編集しました。実行中の合計は $sum という配列に格納され、「単語」のキー値はその実行中の合計の値を格納します。たとえば、$sum['wake'] は単語 wake などの実行中の合計を格納します。

$sum = array();
foreach($wordlist as $word) //Loop through each word in wordlist
{
    // Getting the value for the word by matching pattern.
    //The number value for each word is stored in an array $word_values, where the key is the word and value is the value for that word.
    // The word is got by matching upto '#'. The first parenthesis matches the word - (\w+)
    //The word is followed by #, single digit(\d), multiple spaces(\s+), then the number value(\S+ matches the rest of the non-space characters)
    //The second parenthesis matches the number value for the word

    preg_match('/(\w+)#\d\s+(\S+)/', $word, $match);  
    $word_ref = $match[1];
    $word_ref_number = $match[2];
    $word_values["$word_ref"] = $word_ref_number;

}

//Assuming $sentence_array to store the array of words used in your string example {"Jumping", "jacks", "wake", "me", "up", "in", "the", "morning"}

foreach ($sentence_array as $word)
{
    if (!array_key_exists("$word", $sum)) $sum["$word"] = 0;
    $sum["$word"] += $word_values["$word"]; 
}

文字列全体を小文字にすると言ったので、大文字と小文字の区別に注意すると仮定しているので、ここには含めません。

于 2012-01-05T11:02:37.983 に答える
0
$sentence = 'Jumping jacks wake me up in the morning';

$words=array();

foreach( explode(' ',$sentence) as $w ){

  if( !array_key_exists($w,$words) ){

   $words[$w]++;

  } else {
    $words[$w]=1;
  }

}

スペースで分解し、その単語がキーとして単語配列にあるかどうかを確認します。そうであれば、それは count( val );をインクリメントします。そうでない場合は、val を 1 に設定します。 $words=array() を再宣言せずに、文ごとにこれをループします

于 2012-01-05T06:00:04.837 に答える