2012-03-02 4 views
0

У меня есть система, которая выводит обзор фильма, когда он выводится, я хочу, чтобы ключевые слова, которые появляются в нем, из двух таблиц - отрицательные и позитивные, чтобы быть в другом цвете любой идеи для этого? Код нижеphp вывод текста с выделенными ключевыми словами

<?php 

// Connect to database 
mysql_connect("sdd", "sdsd", "") or die(mysql_error()); 
mysql_select_db("sdsd") or die(mysql_error()); 

$id = mysql_real_escape_string($_POST['reviewid']); 

//$query = "select * from review where id = '$id'"; 
$query = mysql_fetch_assoc(mysql_query("SELECT filmreview FROM review WHERE id = '$id'")); 
$pos = mysql_query("SELECT word FROM positive"); 
$neg = mysql_query("SELECT word FROM negative"); 


//Variables 
$review_text = $query['filmreview']; 
$good = 0; 
$bad = 0; 


// Gets words in to a text array and converts to lower case 
$cnt_r = array_count_values(array_map('mb_strtolower',str_word_count($review_text, 1))); 

// Gets the positive words and check for the word in the text 
    while($check = mysql_fetch_assoc($pos)){ 
     $lower = mb_strtolower($check['word']); 
    if(isset($cnt_r[$lower])){ 
    $good+= $cnt_r[$lower]; 
    echo $check ['word']; 
    echo "<p>"; 
    } 
    } 

// Gets the negative words and check for the word in the text 
while($check = mysql_fetch_assoc($neg)){ 
    $lower = mb_strtolower($check['word']); 
if(isset($cnt_r[$lower])){ 
    $bad+= $cnt_r[$lower]; 
     echo $check ['word']; 
     echo "<p>"; 
} 
} 


// If there are more positive words than negative than the review is positive 
if ($good > $bad) 
{ 
    echo "<p>"; 
    echo "This is a positive review"; 
    echo "<p>"; 
} 

// If there are more negative words than positive than the review is negative 
else if ($good < $bad) 
{ 
    echo "<p>"; 
    echo "This is a negative review"; 
    echo "<p>"; 
} 

// If there are the same amount of positive and negative words than the review is average 
else if ($good == $bad) 
{ 
    echo "<p>"; 
    echo "This is an average review"; 
    echo "<p>"; 
} 

//Prints out the number of postive and negative words found 
echo "Good words: " . $good . " and Bad words: " . $bad; 
echo "<p>"; 
echo $query ['filmreview']; 
echo "<p>"; 
echo "This is <font color=\"blue\">blue</font>!"; 



echo "<form method='post' action='welcome.html'>"; 
echo "<input type='submit' name='searchagain' value='Search'>"; 
?> 
+0

спасибо за ответы, но я не могу получить какой-либо из них для работы, не знаю, что я делаю неправильно – user1045566

ответ

0

Просто искать и находить ключевые слова в тексте, а затем просто заменить их. Так примерно

if($postivekeyword) { 
     $newpostivekeyword = '<span class="positive">'.$postivekeyword.'</span>'; 
    } 
    if($negativekeyword) { 
     $newnegativekeyword = '<span class="negative">'.$negativekeyword.'</span>'; 
    } 

Тогда просто

$new_review_text = str_replace($postivekeyword, $newpostivekeyword, $review_text); 
+0

Как мне добавить цвета к этому? поскольку ничего не выводится – user1045566

+0

просто добавьте классы в ваш css .negative {color: red; } .позитивный {цвет: черный; } и, конечно же, в файле, где вам нужно где-то echo $ new_review_text; –

+0

по какой-то причине это не работает – user1045566

2

Вы можете использовать классы CSS.

В таблице стилей или в стиле тега внутри вас страницы вы можете создать классы CSS:

p .negative { color: red; } 
p .positive { color: black; } 

Теперь просто добавить класс в пункте, и было бы применить стили, которые вы хотите.

// If there are more positive words than negative than the review is positive 
if ($good > $bad) 
{ 
    echo '<p class="positive">'; 
    echo 'This is a positive review'; 
    echo '</p>'; 
} 

// If there are more negative words than positive than the review is negative 
else if ($good < $bad) 
{ 
    echo '<p class="negative">'; 
    echo 'This is a negative review'; 
    echo '</p>'; 
} 

и т.д .....

+0

, но я хочу, чтобы слова в тексте были окрашены не по типу обзора – user1045566

+0

Если вы просто выбираете слова из абзаца, чтобы цвет, вы можете использовать один и тот же принцип, просто используйте класс span, который вы добавляете к началу и концу каждого слова вместо класса для всего абзаца. – chapman84

-1
  1. попытка прочитать ответ запрос, прямо после того, как вы послали его. Таким образом, вам избежать результатов нескольких запросов забивают память
  2. $cnt_r = array_count_values(array_map('mb_strtolower',str_word_count($review_text, 1))); кажется fraked до версии $cnt_r = str_word_count(mb_strtolower($review_text), 2);
  3. str_word_count не многобайтовая безопасно. В Smarty Я использовал preg_match_all('#[\w\pL]+#u', $review_text, $matches); в качестве основы для str_word_count() UTF-8.
  4. дают PDO приглядеться
  5. дают переменные некоторые идентифицирующие имена
  6. всегда esacape ваш выход правильно - htmlspecialchars() там будет использоваться!
  7. Это 2012 год - мы никогда не используем тег <font>! используйте CSS вместо этого!

<?php 
$query = mysql_fetch_assoc(mysql_query("SELECT filmreview FROM review WHERE id = '$id'")); 
$review_text = $query['filmreview']; 

// Gets words in to a text array and converts to lower case 
$review_words = array_count_values(array_map('mb_strtolower',str_word_count($review_text, 1))); 

$positive_words = array(); 
$negative_words = array(); 
$positive_words_count = 0; 
$negative_words_count = 0; 

// Gets the positive words and check for the word in the text 
$res = mysql_query("SELECT word FROM positive"); 
while ($row = mysql_fetch_assoc($res)){ 
    // why isn't this already stored lower-case in database? 
    $_word = mb_strtolower($row['word']); 
    if (isset($review_words[$_word])){ 
     $positive_words_count += $review_words[$_word]; 
     $positive_words[] = $_word; 
    } 
} 

// Gets the negative words and check for the word in the text 
$res = mysql_query("SELECT word FROM negative"); 
while ($row = mysql_fetch_assoc($res)){ 
    // why isn't this already stored lower-case in database? 
    $_word = mb_strtolower($row['word']); 
    if (isset($review_words[$_word])){ 
     $negative_words_count += $review_words[$_word]; 
     $negative_words[] = $_word; 
    } 
} 

if ($positive_words_count > $negative_words_count) { 
    // If there are more positive words than negative than the review is positive 
    echo "<p>This is a positive review<p>"; 
} elseif ($positive_words_count < $negative_words_count) { 
    // If there are more negative words than positive than the review is negative 
    echo "<p>This is a negative review<p>"; 
} else { 
    // If there are the same amount of positive and negative words than the review is average 
    echo "<p>This is an average review<p>"; 
} 

// highlight positive/negative words 
$review_text = htmlspecialchars($review_text); 
$pattern = '#\b(' . join('|', $positive_words) . ')\b#i'; 
$review_text = preg_replace($pattern, "<span class=\"positive\"\\1</span>", $review_text); 
$pattern = '#\b(' . join('|', $negative_words) . ')\b#i'; 
$review_text = preg_replace($pattern, "<span class=\"negative\"\\1</span>", $review_text); 

//Prints out the number of postive and negative words found 
echo "Good words: " . $positive_words_count . " and Bad words: " . $negative_words_count; 
echo "<p>" . $review_text . "<p>"; 
echo "This is <font color=\"blue\">blue</font>!"; 

и где-то в вашем CSS определяют, что span.negative и span.positive должны выглядеть.

+0

как определить css, я никогда не использовал его до – user1045566

+0

goole для «введения в css «и вы найдете кучу полезных вещей, таких как http://www.w3.org/MarkUp/Guide/Style. – rodneyrehm

+0

, похоже, не работает. – user1045566

Смежные вопросы