我有兩個字串,我需要比較每個句子的單詞。字串是這兩個:
$correctSentence = "The year stations are summer, winter, spring and fall.";
$textSentence = "The year stations are four summer, winter and spring and summer.";
所以,我為每個句子制作陣列,然后我有下一個陣列來比較句子之間不相似的單詞。
$correctArray = ["The", "year", "stations", "are", "summer", "winter", "spring", "and", "fall"];
$textArray = ["The", "year", "stations", "are", "four", "summer", "winter", "and", "spring", "and", "summer"];
我正在以這種形式比較陣列:使用 for 回圈,我將 $textArray 的每個單詞與$correctArray.
如果單詞 of$textArray[$i]與任何單詞 of 都不相似$correctArray,則該單詞將存盤在一個名為 的新陣列中$finalArray。
$finalArray = [];
for($i=0; $i<count($textArray); $i ){
if(!in_array($textArray[$i], $correctArray)){
array_push($finalArray, $textArray[$i]);
}
}
$finalArray 的結果是這樣的:
$finalArray = ["four"];
但我還需要存盤$finalArray這樣重復的單詞$textArray:
$finalArray = ["four", "and", "summer"];
$textSentence因為 "and" 和 "summer" 在and中是重復的$textArray,所以單詞不會與$correctSentenceand的單詞相似$correctArray
我認為解決方案是洗掉$correctArray本節中 if 條件為真時的類似詞:
$finalArray = [];
for($i=0; $i<count($textArray); $i ){
if(!in_array($textArray[$i], $correctArray)){
array_push($finalArray, $textArray[$i]);
//In this section, delete the word of $correctArray
//which is similar of $textArray[$i].
//For example: After comparing "summer" of $textArray[$i] with "summer" of $correctArray.
//The record "summer" of $correctArray should be deleted.
//And this way the following record "summer" of $textArray (which is duplicated)
//should be stored in $finalArray
}
}
uj5u.com熱心網友回復:
您可以計算出現在$textArrayusing中的回圈字串/單詞array_count_values(),并檢查計數值是否大于 1(表示重復)而不是 insert into $finalArray,也可能在插入之前$finalArray您需要檢查字串/單詞是否已存在于內部$finalArray。
$finalArray = [];
for($i=0; $i<count($textArray); $i ){
if(!in_array($textArray[$i], $correctArray)){
array_push($finalArray, $textArray[$i]);
}
// count how many times the string appear in the array
$total_string_in_array = array_count_values($textArray)[$textArray[$i]];
if ($total_string_in_array > 1) {
// check if the duplicate string already exists inside $finalArray
if ( ! in_array($textArray[$i], $finalArray)) {
array_push($finalArray, $textArray[$i]);
}
}
}
參考:
- array_count_values():https ://www.php.net/manual/en/function.array-count-values.php
uj5u.com熱心網友回復:
PHP 為您完成此任務所需的一切提供了本機函式。
- 從沒有標點符號的句子中提取單詞
str_word_count()。 - 用 查找兩個平面陣列之間的差異
array_diff()。 - 用 計算陣列中值的出現次數
array_count_values()。 - 使用 洗掉值(計數)小于 2 的元素
array_filter()。 - 使用 . 獲取陣列鍵
array_keys()。 - 合并兩個陣列
array_merge()。
代碼:(演示)
$correctSentence = "The year stations are summer, winter, spring and fall.";
$textSentence = "The year stations are four summer, winter and spring and summer.";
$correctArray = str_word_count($correctSentence, 1);
$textArray = str_word_count($textSentence, 1);
var_export(
array_merge(
array_diff($textArray, $correctArray),
array_keys(array_filter(array_count_values($textArray), fn($v) => $v > 1))
)
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/515198.html
