文章目录
-
- 在当今数字化时代,网络传媒机构面临着海量的舆情信息。传统的舆情监测方法往往刚性有余而柔性不足,难以适应快速变化的网络环境。柔性舆情监测强调自适应、智能化和实时响应,能够帮助传媒机构更精准地把握舆论动向,及时做出反应。 本教程将介绍如何通过开发一个WordPress插件,实现柔性舆情监测与响应系统。我们将从基础架构开始,逐步实现舆情数据采集、情感分析、预警机制和响应建议等功能。
- 首先,我们需要创建一个标准的WordPress插件结构: <?php /** * 插件名称: 柔性舆情监测与响应系统 * 插件URI: https://yourwebsite.com/ * 描述: 用于网络传媒机构的柔性舆情监测与响应WordPress插件 * 版本: 1.0.0 * 作者: 您的名称 * 作者URI: https://yourauthorwebsite.com/ * 许可证: GPL v2或更高版本 */ // 防止直接访问 if (!defined('ABSPATH')) { exit; } // 定义插件常量 define('FOMR_PLUGIN_VERSION', '1.0.0'); define('FOMR_PLUGIN_DIR', plugin_dir_path(__FILE__)); define('FOMR_PLUGIN_URL', plugin_dir_url(__FILE__)); // 主插件类 class Flexible_Opinion_Monitoring_Response { private static $instance = null; // 获取单例实例 public static function get_instance() { if (null === self::$instance) { self::$instance = new self(); } return self::$instance; } // 构造函数 private function __construct() { $this->init_hooks(); $this->includes(); } // 初始化钩子 private function init_hooks() { // 激活/停用钩子 register_activation_hook(__FILE__, array($this, 'activate')); register_deactivation_hook(__FILE__, array($this, 'deactivate')); // 管理菜单 add_action('admin_menu', array($this, 'add_admin_menu')); // 初始化 add_action('init', array($this, 'init')); } // 包含必要文件 private function includes() { require_once FOMR_PLUGIN_DIR . 'includes/class-data-collector.php'; require_once FOMR_PLUGIN_DIR . 'includes/class-sentiment-analyzer.php'; require_once FOMR_PLUGIN_DIR . 'includes/class-alert-system.php'; require_once FOMR_PLUGIN_DIR . 'includes/class-response-suggestor.php'; } // 插件激活时执行 public function activate() { // 创建必要的数据库表 $this->create_tables(); // 设置默认选项 $this->set_default_options(); // 添加版本号 update_option('fomr_plugin_version', FOMR_PLUGIN_VERSION); } // 插件停用时执行 public function deactivate() { // 清理定时任务 $this->clear_scheduled_events(); } // 初始化 public function init() { // 加载文本域 load_plugin_textdomain('fomr', false, dirname(plugin_basename(__FILE__)) . '/languages'); } // 添加管理菜单 public function add_admin_menu() { add_menu_page( '舆情监测系统', // 页面标题 '舆情监测', // 菜单标题 'manage_options', // 权限 'fomr-dashboard', // 菜单slug array($this, 'display_dashboard'), // 回调函数 'dashicons-chart-line', // 图标 30 // 位置 ); // 添加子菜单 add_submenu_page( 'fomr-dashboard', '监测设置', '监测设置', 'manage_options', 'fomr-settings', array($this, 'display_settings') ); } // 显示仪表板 public function display_dashboard() { include FOMR_PLUGIN_DIR . 'admin/views/dashboard.php'; } // 显示设置页面 public function display_settings() { include FOMR_PLUGIN_DIR . 'admin/views/settings.php'; } // 创建数据库表 private function create_tables() { global $wpdb; $charset_collate = $wpdb->get_charset_collate(); $table_name = $wpdb->prefix . 'fomr_opinion_data'; $sql = "CREATE TABLE IF NOT EXISTS $table_name ( id bigint(20) NOT NULL AUTO_INCREMENT, source varchar(200) NOT NULL, content text NOT NULL, sentiment_score float DEFAULT 0, sentiment_label varchar(50) DEFAULT 'neutral', keywords text, author varchar(200), publish_time datetime DEFAULT CURRENT_TIMESTAMP, collected_time datetime DEFAULT CURRENT_TIMESTAMP, response_status varchar(50) DEFAULT 'pending', PRIMARY KEY (id), KEY sentiment_score (sentiment_score), KEY publish_time (publish_time) ) $charset_collate;"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); } // 设置默认选项 private function set_default_options() { $default_options = array( 'monitoring_keywords' => array('品牌名', '行业关键词'), 'monitoring_sources' => array('weibo', 'weixin', 'news'), 'sentiment_threshold' => 0.7, 'alert_email' => get_option('admin_email'), 'auto_response' => false, 'update_frequency' => 'hourly' ); add_option('fomr_options', $default_options); } // 清理定时任务 private function clear_scheduled_events() { wp_clear_scheduled_hook('fomr_collect_data_event'); wp_clear_scheduled_hook('fomr_analyze_data_event'); } } // 初始化插件 function fomr_init() { return Flexible_Opinion_Monitoring_Response::get_instance(); } // 启动插件 add_action('plugins_loaded', 'fomr_init'); ?>
- 数据采集是舆情监测的基础。以下是一个数据采集类的实现: <?php /** * 舆情数据采集类 * 负责从不同来源收集舆情数据 */ class FOMR_Data_Collector { private $options; public function __construct() { $this->options = get_option('fomr_options'); } /** * 开始数据采集流程 */ public function collect_data() { $keywords = $this->options['monitoring_keywords']; $sources = $this->options['monitoring_sources']; $all_data = array(); foreach ($keywords as $keyword) { foreach ($sources as $source) { $data = $this->collect_from_source($source, $keyword); if (!empty($data)) { $all_data = array_merge($all_data, $data); } } } // 保存数据到数据库 $this->save_to_database($all_data); return count($all_data); } /** * 从指定来源采集数据 * @param string $source 数据来源 * @param string $keyword 关键词 * @return array 采集到的数据 */ private function collect_from_source($source, $keyword) { $collected_data = array(); switch ($source) { case 'weibo': $collected_data = $this->collect_from_weibo($keyword); break; case 'weixin': $collected_data = $this->collect_from_weixin($keyword); break; case 'news': $collected_data = $this->collect_from_news($keyword); break; case 'forum': $collected_data = $this->collect_from_forum($keyword); break; } return $collected_data; } /** * 模拟从微博采集数据 * @param string $keyword 关键词 * @return array 微博数据 */ private function collect_from_weibo($keyword) { // 这里应该调用微博API,此处为模拟数据 $mock_data = array( array( 'source' => 'weibo', 'content' => "关于{$keyword}的最新讨论,用户反馈积极", 'author' => '微博用户A', 'publish_time' => date('Y-m-d H:i:s', strtotime('-1 hour')) ), array( 'source' => 'weibo', 'content' => "{$keyword}出现问题,用户投诉较多", 'author' => '微博用户B', 'publish_time' => date('Y-m-d H:i:s', strtotime('-2 hours')) ) ); return $mock_data; } /** * 模拟从微信公众号采集数据 * @param string $keyword 关键词 * @return array 微信数据 */ private function collect_from_weixin($keyword) { // 这里应该调用微信API,此处为模拟数据 $mock_data = array( array( 'source' => 'weixin', 'content' => "深度分析{$keyword}的市场表现", 'author' => '行业公众号', 'publish_time' => date('Y-m-d H:i:s', strtotime('-3 hours')) ) ); return $mock_data; } /** * 模拟从新闻网站采集数据 * @param string $keyword 关键词 * @return array 新闻数据 */ private function collect_from_news($keyword) { // 这里应该调用新闻API或使用爬虫,此处为模拟数据 $mock_data = array( array( 'source' => 'news', 'content' => "{$keyword}获得行业大奖,市场前景看好", 'author' => '财经新闻网', 'publish_time' => date('Y-m-d H:i:s', strtotime('-5 hours')) ) ); return $mock_data; } /** * 模拟从论坛采集数据 * @param string $keyword 关键词 * @return array 论坛数据 */ private function collect_from_forum($keyword) { // 这里应该调用论坛API或使用爬虫,此处为模拟数据 $mock_data = array( array( 'source' => 'forum', 'content' => "讨论:{$keyword}的使用体验分享", 'author' => '论坛用户C', 'publish_time' => date('Y-m-d H:i:s', strtotime('-4 hours')) ) ); return $mock_data; } /** * 保存数据到数据库 * @param array $data 舆情数据 */ private function save_to_database($data) { global $wpdb; $table_name = $wpdb->prefix . 'fomr_opinion_data'; foreach ($data as $item) { // 检查是否已存在相同内容 $exists = $wpdb->get_var($wpdb->prepare( "SELECT COUNT(*) FROM $table_name WHERE content = %s AND source = %s", $item['content'], $item['source'] )); if (!$exists) { $wpdb->insert( $table_name, array( 'source' => $item['source'], 'content' => $item['content'], 'author' => $item['author'], 'publish_time' => $item['publish_time'], 'collected_time' => current_time('mysql') ), array('%s', '%s', '%s', '%s', '%s') ); } } } /** * 设置定时采集任务 */ public function schedule_collection() { if (!wp_next_scheduled('fomr_collect_data_event')) { $frequency = isset($this->options['update_frequency']) ? $this->options['update_frequency'] : 'hourly'; switch ($frequency) { case 'hourly': $interval = HOUR_IN_SECONDS; break; case 'twicedaily': $interval = 12 * HOUR_IN_SECONDS; break; case 'daily': $interval = DAY_IN_SECONDS; break; default: $interval = HOUR_IN_SECONDS; } wp_schedule_event(time(), $frequency, 'fomr_collect_data_event'); } add_action('fomr_collect_data_event', array($this, 'collect_data')); } } ?>
- 情感分析是柔性舆情监测的核心,以下是一个简单的情感分析类: <?php /** * 情感分析类 * 使用简单算法进行情感分析,实际应用中可替换为更复杂的AI模型 */ class FOMR_Sentiment_Analyzer { // 情感词典 private $positive_words = array( '好', '优秀', '满意', '喜欢', '赞', '支持', '推荐', '棒', '出色', '卓越', '高兴', '愉快', '惊喜', '感谢', '棒极了', '完美', '一流', '超值', '实惠' ); private $negative_words = array( '差', '糟糕', '不满意', '讨厌', '批评', '反对', '垃圾', '烂', '差劲', '劣质', '生气', '失望', '愤怒', '投诉', '问题', '故障', '缺陷', '昂贵', '不值' ); /** * 分析文本情感 * @param string $text 待分析文本 * @return array 情感分析结果 */ public function analyze($text) { // 简单情感分析算法 $positive_score = 0; $negative_score = 0; // 检查积极词汇 foreach ($this->positive_words as $word) { if (mb_strpos($text, $word) !== false) { $positive_score++; } } // 检查消极词汇 foreach ($this->negative_words as $word) { if (mb_strpos($text, $word) !== false) { $negative_score++; } } // 计算情感得分(-1到1之间) $total = $positive_score + $negative_score; if ($total > 0) { $sentiment_score = ($positive_score - $negative_score) / $total; } else { $sentiment_score = 0; } // 确定情感标签 if ($sentiment_score > 0.3) { $sentiment_label = 'positive'; } elseif ($sentiment_score < -0.3) { $sentiment_label = 'negative'; } else { $sentiment_label = 'neutral'; } // 提取关键词 $keywords = $this->extract_keywords($text); return array( 'score' => $sentiment_score, 'label' => $sentiment_label, 'positive_count' => $positive_score, 'negative_count' => $negative_score, 'keywords' => $keywords ); } /** * 提取关键词(简单实现) * @param string $text 文本内容 * @return array 关键词数组 */ private function extract_keywords($text) { // 去除标点符号 $text = preg_replace('/[^wx{4e00}-x{9fa5}]+/u', ' ', $text); // 分词(简单按空格分割,实际应用中应使用分词库) $words = explode(' ', $text); // 过滤停用词 $stop_words = array('的', '了', '在', '是', '我', '有', '和', '就', '不', '人', '都', '一', '一个', '上', '也', '很', '到', '说', '要', '去', '你', '会', '着', '没有', '看', '好', '自己', '这'); $filtered_words = array_diff($words, $stop_words); // 统计词频 $word_counts = array_count_values($filtered_words); // 按词频排序 arsort($word_counts); // 取前5个作为关键词 $keywords = array_slice(array_keys($word_counts), 0, 5); return $keywords; } /** * 批量分析舆情数据 */ public function batch_analyze() { global $wpdb; $table_name = $wpdb->prefix . 'fomr_opinion_data'; // 获取未分析的数据 $unanalyzed_data = $wpdb->get_results( "SELECT * FROM $table_name WHERE sentiment_score = 0 AND sentiment_label = 'neutral' LIMIT 50" ); foreach ($unanalyzed_data as $data) { $analysis_result = $this->analyze($data->content); // 更新数据库 $wpdb->update( $table_name, array( 'sentiment_score' => $analysis_result['score'], 'sentiment_label' => $analysis_result['label'], 'keywords' => implode(',', $analysis_result['keywords']) ), array('id' => $data->id), array('%f', '%s', '%s'), array('%d') ); } return count($unanalyzed_data); } } ?>
- 预警系统是舆情监测的关键环节,以下实现一个智能预警类: <?php /** * 舆情预警系统类 * 负责监测舆情变化并触发预警 */ class FOMR_Alert_System { private $options; public function __construct() { $this->options = get_option('fomr_options'); } /** * 检查并触发预警 */ public function check_alerts() { global $wpdb; $table_name = $wpdb->prefix . 'fomr_opinion_data'; // 获取最近24小时的舆情数据 $recent_data = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $table_name WHERE collected_time >= %s ORDER BY collected_time DESC", date('Y-m-d H:i:s', strtotime('-24 hours')) ) ); $alerts = array(); // 检查负面舆情激增 $negative_surge = $this->check_negative_surge($recent_data); if ($negative_surge) { $alerts[] = $negative_surge; } // 检查关键词突现 $keyword_emergence = $this->check_keyword_emergence($recent_data); if ($keyword_emergence) { $alerts[] = $keyword_emergence; } // 检查情感趋势变化 $sentiment_trend = $this->check_sentiment_trend($recent_data); if ($sentiment_trend) { $alerts[] = $sentiment_trend; } // 如果有预警,发送通知 if (!empty($alerts)) { $this->send_alerts($alerts); } return $alerts; } /** * 检查负面舆情激增 * @param array $data 舆情数据 * @return array|bool 预警信息或false */ private function check_negative_surge($data) { $threshold = isset($this->options['sentiment_threshold']) ? $this->options['sentiment_threshold'] : 0.7; $negative_count = 0; $total_count = count($data); foreach ($data as $item) { if ($item->sentiment_label == 'negative' && abs($item->sentiment_score) > $threshold) { $negative_count++; } } if ($total_count > 0) { $negative_ratio = $negative_count / $total_count; // 如果负面舆情比例超过30%,触发预警 if ($negative_ratio > 0.3 && $negative_count >= 5) { return array( 'type' => 'negative_surge', 'level' => $negative_ratio > 0.5 ? 'high' : 'medium', 'message' => sprintf( '检测到负面舆情激增:最近24小时共%d条舆情,其中%d条为负面(占比%.1f%%)', $total_count, $negative_count, $negative_ratio * 100 ), 'data' => array( 'total_count' => $total_count, 'negative_count' => $negative_count, 'ratio' => $negative_ratio ) ); } } return false; } /** * 检查关键词突现 * @param array $data 舆情数据 * @return array|bool 预警信息或false */ private function check_keyword_emergence($data) { $all_keywords = array(); // 收集所有关键词 foreach ($data as $item) { if (!empty($item->keywords)) { $keywords = explode(',', $item->keywords); $all_keywords = array_merge($all_keywords, $keywords); } } // 统计词频 $keyword_counts = array_count_values($all_keywords); // 找出高频关键词(出现3次以上) $emerging_keywords = array(); foreach ($keyword_counts as $keyword => $count) { if ($count >= 3 && strlen($keyword) > 1) { $emerging_keywords[$keyword] = $count; } } if (!empty($emerging_keywords)) { arsort($emerging_keywords); return array( 'type' => 'keyword_emergence', 'level' => 'medium', 'message' => '检测到关键词突现:' . implode('、', array_keys(array_slice($emerging_keywords, 0, 3))), 'data' => $emerging_keywords ); } return false; } /** * 检查情感趋势变化 * @param array $data 舆情数据 * @return array|bool 预警信息或false */ private function check_sentiment_trend($data) { if (count($data) < 10) { return false; } // 按时间分组(每4小时一组) $time_groups = array(); foreach ($data as $item) { $hour = date('H', strtotime($item->collected_time)); $group = floor($hour / 4); if (!isset($time_groups[$group])) { $time_groups[$group] = array( 'count' => 0, 'total_score' => 0 ); } $time_groups[$group]['count']++; $time_groups[$group]['total_score'] += $item->sentiment_score; } // 计算每组平均情感得分 $averages = array(); foreach ($time_groups as $group => $stats) { if ($stats['count'] > 0) { $averages[$group] = $stats['total_score'] / $stats['count']; } } // 检查趋势(最近两组与前两组比较) if (count($averages) >= 4) { $recent_avg = array_slice($averages, 0, 2); $previous_avg = array_slice($averages, 2, 2); $recent_score = array_sum($recent_avg) / count($recent_avg); $previous_score = array_sum($previous_avg) / count($previous_avg); // 如果情感得分下降超过0.5,触发预警 if (($previous_score - $recent_score) > 0.5) { return array( 'type' => 'sentiment_decline', 'level' => 'medium', 'message' => sprintf( '检测到情感趋势下降:近期情感得分从%.2f下降至%.2f', $previous_score, $recent_score ), 'data' => array( 'previous_score' => $previous_score, 'recent_score' => $recent_score, 'change' => $previous_score - $recent_score ) ); } } return false; } /** * 发送预警通知 * @param array $alerts 预警信息数组 */ private function send_alerts($alerts) { $email = isset($this->options['alert_email']) ? $this->options['alert_email'] : get_option('admin_email'); $subject = '舆情监测系统预警通知'; $message = "<h2>舆情监测系统预警通知</h2>n"; $message .= "<p>检测时间:" . date('Y-m-d H:i:s') . "</p>n"; $message .= "<hr>n"; foreach ($alerts as $index => $alert) { $level_color = $alert['level'] == 'high' ? 'red' : ($alert['level'] == 'medium' ? 'orange' : 'blue'); $message .= "<div style='border: 1px solid #ccc; padding: 10px; margin: 10px 0;'>n"; $message .= "<h3 style='color: {$level_color};'>预警#" . ($index + 1) . " - " . $this->get_alert_type_name($alert['type']) . "</h3>n"; $message .= "<p><strong>级别:</strong>" . ($alert['level'] == 'high' ? '高' : ($alert['level'] == 'medium' ? '中' : '低')) . "</p>n"; $message .= "<p><strong>描述:</strong>" . $alert['message'] . "</p>n"; if (!empty($alert['data'])) { $message .= "<p><strong>详细数据:</strong></p>n"; $message .= "<pre>" . print_r($alert['data'], true) . "</pre>n"; } $message .= "</div>n"; } $message .= "<hr>n"; $message .= "<p>请登录<a href='" . admin_url('admin.php?page=fomr-dashboard') . "'>舆情监测系统</a>查看详情。</p>n"; // 发送邮件 $headers = array('Content-Type: text/html; charset=UTF-8'); wp_mail($email, $subject, $message, $headers); // 同时记录到系统日志 $this->log_alerts($alerts); } /** * 获取预警类型名称 * @param string $type 预警类型 * @return string 类型名称 */ private function get_alert_type_name($type) { $names = array( 'negative_surge' => '负面舆情激增', 'keyword_emergence' => '关键词突现', 'sentiment_decline' => '情感趋势下降' ); return isset($names[$type]) ? $names[$type] : $type; } /** * 记录预警日志 * @param array $alerts 预警信息 */ private function log_alerts($alerts) { global $wpdb; $table_name = $wpdb->prefix . 'fomr_alert_logs'; foreach ($alerts as $alert) { $wpdb->insert( $table_name, array( 'alert_type' => $alert['type'], 'alert_level' => $alert['level'], 'alert_message' => $alert['message'], 'alert_data' => maybe_serialize($alert['data']), 'created_time' => current_time('mysql') ), array('%s', '%s', '%s', '%s', '%s') ); } } /** * 设置定时预警检查 */ public function schedule_alert_check() { if (!wp_next_scheduled('fomr_check_alerts_event')) { wp_schedule_event(time(), 'hourly', 'fomr_check_alerts_event'); } add_action('fomr_check_alerts_event', array($this, 'check_alerts')); } } ?>
- 响应建议系统帮助编辑快速制定应对策略: <?php /** * 智能响应建议类 * 根据舆情分析结果生成响应建议 */ class FOMR_Response_Suggestor { /** * 生成响应建议 * @param int $data_id 舆情数据ID * @return array 响应建议 */ public function generate_suggestions($data_id) { global $wpdb; $table_name = $wpdb->prefix . 'fomr_opinion_data'; // 获取舆情数据 $data = $wpdb->get_row($wpdb->prepare( "SELECT * FROM $table_name WHERE id = %d", $data_id )); if (!$data) { return array('error' => '数据不存在'); } $suggestions = array(); // 根据情感标签生成建议 switch ($data->sentiment_label) { case 'positive': $suggestions = $this->suggest_for_positive($data); break; case 'negative': $suggestions = $this->suggest_for_negative($data); break; case 'neutral': $suggestions = $this->suggest_for_neutral($data); break; } // 根据来源生成额外建议 $source_suggestions = $this->suggest_by_source($data); $suggestions = array_merge($suggestions, $source_suggestions); // 保存建议到数据库 $this->save_suggestions($data_id, $suggestions); return $suggestions; } /** * 针对正面舆情的建议 * @param object $data 舆情数据 * @return array 建议数组 */ private function suggest_for_positive($data) { $suggestions = array(); // 根据情感得分调整建议强度 $strength = $data->sentiment_score > 0.7 ? 'strong' : 'moderate'; $suggestions[] = array( 'type' => 'amplify', 'title' => '放大正面声音', 'content' => $this->get_amplify_suggestion($data, $strength), 'priority' => 1 ); $suggestions[] = array( 'type' => 'engage', 'title' => '加强用户互动', 'content' => '在相关平台回复感谢用户,邀请分享更多正面体验', 'priority' => 2 ); if ($strength == 'strong') { $suggestions[] = array( 'type' => 'leverage', 'title' => '利用口碑传播', 'content' => '考虑将用户正面评价用于宣传材料,制作案例分享', 'priority' => 3 ); } return $suggestions; } /** * 针对负面舆情的建议 * @param object $data 舆情数据 * @return array 建议数组 */ private function suggest_for_negative($data) { $suggestions = array(); $severity = abs($data->sentiment_score) > 0.7 ? 'severe' : 'moderate'; $suggestions[] = array( 'type' => 'respond', 'title' => '及时响应', 'content' => $this->get_response_suggestion($data, $severity), 'priority' => 1, 'urgency' => $severity == 'severe' ? 'high' : 'medium' ); $suggestions[] = array( 'type' => 'investigate', 'title' => '问题调查', 'content' => '检查是否系统性问题,收集更多用户反馈', 'priority' => 2, 'urgency' => 'medium' ); if ($severity == 'severe') { $suggestions[] = array( 'type' => 'escalate', 'title' => '升级处理', 'content' => '通知相关部门负责人,制定专项解决方案', 'priority' => 1, 'urgency' => 'high' ); } return $suggestions; } /** * 针对中性舆情的建议 * @param object $data 舆情数据 * @return array 建议数组 */ private function suggest_for_neutral($data) { return array( array( 'type' => 'monitor', 'title' => '持续监测', 'content' => '保持关注,观察舆情发展趋势', 'priority' => 3, 'urgency' => 'low' ), array( 'type' => 'engage', 'title' => '引导讨论', 'content' => '可以主动发起相关话题讨论,引导用户表达观点', 'priority' => 2, 'urgency' => 'low' ) ); } /** * 根据数据来源生成建议 * @param object $data 舆情数据 * @return array 建议数组 */ private function suggest_by_source($data) { $suggestions = array(); switch ($data->source) { case 'weibo': $suggestions[] = array( 'type' => 'platform_specific', 'title' => '微博平台策略', 'content' => '考虑使用微博的转发、话题功能扩大影响', 'priority' => 2 ); break; case 'weixin': $suggestions[] = array( 'type' => 'platform_specific', 'title' => '微信平台策略', 'content' => '可通过公众号文章或朋友圈进行深度沟通', 'priority' => 2 ); break; case 'news': $suggestions[] = array( 'type' => 'platform_specific', 'title' => '新闻媒体策略', 'content' => '考虑准备新闻稿或媒体声明', 'priority' => 2 ); break; } return $suggestions; } /** * 获取放大建议的具体内容 * @param object $data 舆情数据 * @param string $strength 强度 * @return string 建议内容 */ private function get_amplify_suggestion($data, $strength) { $templates = array( 'strong' => '该正面评价情感强烈(得分%.2f),建议重点推广。可联系用户获取详细使用体验,制作成案例研究。', 'moderate' => '该正面评价情感积极(得分%.2f),可进行常规推广。在相关渠道分享用户好评,增强品牌信誉。' ); return sprintf( $templates[$strength], $data->sentiment_score );
在当今数字化时代,网络传媒机构面临着海量的舆情信息。传统的舆情监测方法往往刚性有余而柔性不足,难以适应快速变化的网络环境。柔性舆情监测强调自适应、智能化和实时响应,能够帮助传媒机构更精准地把握舆论动向,及时做出反应。
本教程将介绍如何通过开发一个WordPress插件,实现柔性舆情监测与响应系统。我们将从基础架构开始,逐步实现舆情数据采集、情感分析、预警机制和响应建议等功能。
首先,我们需要创建一个标准的WordPress插件结构:
<?php
/**
* 插件名称: 柔性舆情监测与响应系统
* 插件URI: https://yourwebsite.com/
* 描述: 用于网络传媒机构的柔性舆情监测与响应WordPress插件
* 版本: 1.0.0
* 作者: 您的名称
* 作者URI: https://yourauthorwebsite.com/
* 许可证: GPL v2或更高版本
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
// 定义插件常量
define('FOMR_PLUGIN_VERSION', '1.0.0');
define('FOMR_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('FOMR_PLUGIN_URL', plugin_dir_url(__FILE__));
// 主插件类
class Flexible_Opinion_Monitoring_Response {
private static $instance = null;
// 获取单例实例
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
// 构造函数
private function __construct() {
$this->init_hooks();
$this->includes();
}
// 初始化钩子
private function init_hooks() {
// 激活/停用钩子
register_activation_hook(__FILE__, array($this, 'activate'));
register_deactivation_hook(__FILE__, array($this, 'deactivate'));
// 管理菜单
add_action('admin_menu', array($this, 'add_admin_menu'));
// 初始化
add_action('init', array($this, 'init'));
}
// 包含必要文件
private function includes() {
require_once FOMR_PLUGIN_DIR . 'includes/class-data-collector.php';
require_once FOMR_PLUGIN_DIR . 'includes/class-sentiment-analyzer.php';
require_once FOMR_PLUGIN_DIR . 'includes/class-alert-system.php';
require_once FOMR_PLUGIN_DIR . 'includes/class-response-suggestor.php';
}
// 插件激活时执行
public function activate() {
// 创建必要的数据库表
$this->create_tables();
// 设置默认选项
$this->set_default_options();
// 添加版本号
update_option('fomr_plugin_version', FOMR_PLUGIN_VERSION);
}
// 插件停用时执行
public function deactivate() {
// 清理定时任务
$this->clear_scheduled_events();
}
// 初始化
public function init() {
// 加载文本域
load_plugin_textdomain('fomr', false, dirname(plugin_basename(__FILE__)) . '/languages');
}
// 添加管理菜单
public function add_admin_menu() {
add_menu_page(
'舆情监测系统', // 页面标题
'舆情监测', // 菜单标题
'manage_options', // 权限
'fomr-dashboard', // 菜单slug
array($this, 'display_dashboard'), // 回调函数
'dashicons-chart-line', // 图标
30 // 位置
);
// 添加子菜单
add_submenu_page(
'fomr-dashboard',
'监测设置',
'监测设置',
'manage_options',
'fomr-settings',
array($this, 'display_settings')
);
}
// 显示仪表板
public function display_dashboard() {
include FOMR_PLUGIN_DIR . 'admin/views/dashboard.php';
}
// 显示设置页面
public function display_settings() {
include FOMR_PLUGIN_DIR . 'admin/views/settings.php';
}
// 创建数据库表
private function create_tables() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . 'fomr_opinion_data';
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id bigint(20) NOT NULL AUTO_INCREMENT,
source varchar(200) NOT NULL,
content text NOT NULL,
sentiment_score float DEFAULT 0,
sentiment_label varchar(50) DEFAULT 'neutral',
keywords text,
author varchar(200),
publish_time datetime DEFAULT CURRENT_TIMESTAMP,
collected_time datetime DEFAULT CURRENT_TIMESTAMP,
response_status varchar(50) DEFAULT 'pending',
PRIMARY KEY (id),
KEY sentiment_score (sentiment_score),
KEY publish_time (publish_time)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
// 设置默认选项
private function set_default_options() {
$default_options = array(
'monitoring_keywords' => array('品牌名', '行业关键词'),
'monitoring_sources' => array('weibo', 'weixin', 'news'),
'sentiment_threshold' => 0.7,
'alert_email' => get_option('admin_email'),
'auto_response' => false,
'update_frequency' => 'hourly'
);
add_option('fomr_options', $default_options);
}
// 清理定时任务
private function clear_scheduled_events() {
wp_clear_scheduled_hook('fomr_collect_data_event');
wp_clear_scheduled_hook('fomr_analyze_data_event');
}
}
// 初始化插件
function fomr_init() {
return Flexible_Opinion_Monitoring_Response::get_instance();
}
// 启动插件
add_action('plugins_loaded', 'fomr_init');
?>
数据采集是舆情监测的基础。以下是一个数据采集类的实现:
<?php
/**
* 舆情数据采集类
* 负责从不同来源收集舆情数据
*/
class FOMR_Data_Collector {
private $options;
public function __construct() {
$this->options = get_option('fomr_options');
}
/**
* 开始数据采集流程
*/
public function collect_data() {
$keywords = $this->options['monitoring_keywords'];
$sources = $this->options['monitoring_sources'];
$all_data = array();
foreach ($keywords as $keyword) {
foreach ($sources as $source) {
$data = $this->collect_from_source($source, $keyword);
if (!empty($data)) {
$all_data = array_merge($all_data, $data);
}
}
}
// 保存数据到数据库
$this->save_to_database($all_data);
return count($all_data);
}
/**
* 从指定来源采集数据
* @param string $source 数据来源
* @param string $keyword 关键词
* @return array 采集到的数据
*/
private function collect_from_source($source, $keyword) {
$collected_data = array();
switch ($source) {
case 'weibo':
$collected_data = $this->collect_from_weibo($keyword);
break;
case 'weixin':
$collected_data = $this->collect_from_weixin($keyword);
break;
case 'news':
$collected_data = $this->collect_from_news($keyword);
break;
case 'forum':
$collected_data = $this->collect_from_forum($keyword);
break;
}
return $collected_data;
}
/**
* 模拟从微博采集数据
* @param string $keyword 关键词
* @return array 微博数据
*/
private function collect_from_weibo($keyword) {
// 这里应该调用微博API,此处为模拟数据
$mock_data = array(
array(
'source' => 'weibo',
'content' => "关于{$keyword}的最新讨论,用户反馈积极",
'author' => '微博用户A',
'publish_time' => date('Y-m-d H:i:s', strtotime('-1 hour'))
),
array(
'source' => 'weibo',
'content' => "{$keyword}出现问题,用户投诉较多",
'author' => '微博用户B',
'publish_time' => date('Y-m-d H:i:s', strtotime('-2 hours'))
)
);
return $mock_data;
}
/**
* 模拟从微信公众号采集数据
* @param string $keyword 关键词
* @return array 微信数据
*/
private function collect_from_weixin($keyword) {
// 这里应该调用微信API,此处为模拟数据
$mock_data = array(
array(
'source' => 'weixin',
'content' => "深度分析{$keyword}的市场表现",
'author' => '行业公众号',
'publish_time' => date('Y-m-d H:i:s', strtotime('-3 hours'))
)
);
return $mock_data;
}
/**
* 模拟从新闻网站采集数据
* @param string $keyword 关键词
* @return array 新闻数据
*/
private function collect_from_news($keyword) {
// 这里应该调用新闻API或使用爬虫,此处为模拟数据
$mock_data = array(
array(
'source' => 'news',
'content' => "{$keyword}获得行业大奖,市场前景看好",
'author' => '财经新闻网',
'publish_time' => date('Y-m-d H:i:s', strtotime('-5 hours'))
)
);
return $mock_data;
}
/**
* 模拟从论坛采集数据
* @param string $keyword 关键词
* @return array 论坛数据
*/
private function collect_from_forum($keyword) {
// 这里应该调用论坛API或使用爬虫,此处为模拟数据
$mock_data = array(
array(
'source' => 'forum',
'content' => "讨论:{$keyword}的使用体验分享",
'author' => '论坛用户C',
'publish_time' => date('Y-m-d H:i:s', strtotime('-4 hours'))
)
);
return $mock_data;
}
/**
* 保存数据到数据库
* @param array $data 舆情数据
*/
private function save_to_database($data) {
global $wpdb;
$table_name = $wpdb->prefix . 'fomr_opinion_data';
foreach ($data as $item) {
// 检查是否已存在相同内容
$exists = $wpdb->get_var($wpdb->prepare(
"SELECT COUNT(*) FROM $table_name WHERE content = %s AND source = %s",
$item['content'],
$item['source']
));
if (!$exists) {
$wpdb->insert(
$table_name,
array(
'source' => $item['source'],
'content' => $item['content'],
'author' => $item['author'],
'publish_time' => $item['publish_time'],
'collected_time' => current_time('mysql')
),
array('%s', '%s', '%s', '%s', '%s')
);
}
}
}
/**
* 设置定时采集任务
*/
public function schedule_collection() {
if (!wp_next_scheduled('fomr_collect_data_event')) {
$frequency = isset($this->options['update_frequency']) ? $this->options['update_frequency'] : 'hourly';
switch ($frequency) {
case 'hourly':
$interval = HOUR_IN_SECONDS;
break;
case 'twicedaily':
$interval = 12 * HOUR_IN_SECONDS;
break;
case 'daily':
$interval = DAY_IN_SECONDS;
break;
default:
$interval = HOUR_IN_SECONDS;
}
wp_schedule_event(time(), $frequency, 'fomr_collect_data_event');
}
add_action('fomr_collect_data_event', array($this, 'collect_data'));
}
}
?>
情感分析是柔性舆情监测的核心,以下是一个简单的情感分析类:
<?php
/**
* 情感分析类
* 使用简单算法进行情感分析,实际应用中可替换为更复杂的AI模型
*/
class FOMR_Sentiment_Analyzer {
// 情感词典
private $positive_words = array(
'好', '优秀', '满意', '喜欢', '赞', '支持', '推荐', '棒', '出色', '卓越',
'高兴', '愉快', '惊喜', '感谢', '棒极了', '完美', '一流', '超值', '实惠'
);
private $negative_words = array(
'差', '糟糕', '不满意', '讨厌', '批评', '反对', '垃圾', '烂', '差劲', '劣质',
'生气', '失望', '愤怒', '投诉', '问题', '故障', '缺陷', '昂贵', '不值'
);
/**
* 分析文本情感
* @param string $text 待分析文本
* @return array 情感分析结果
*/
public function analyze($text) {
// 简单情感分析算法
$positive_score = 0;
$negative_score = 0;
// 检查积极词汇
foreach ($this->positive_words as $word) {
if (mb_strpos($text, $word) !== false) {
$positive_score++;
}
}
// 检查消极词汇
foreach ($this->negative_words as $word) {
if (mb_strpos($text, $word) !== false) {
$negative_score++;
}
}
// 计算情感得分(-1到1之间)
$total = $positive_score + $negative_score;
if ($total > 0) {
$sentiment_score = ($positive_score - $negative_score) / $total;
} else {
$sentiment_score = 0;
}
// 确定情感标签
if ($sentiment_score > 0.3) {
$sentiment_label = 'positive';
} elseif ($sentiment_score < -0.3) {
$sentiment_label = 'negative';
} else {
$sentiment_label = 'neutral';
}
// 提取关键词
$keywords = $this->extract_keywords($text);
return array(
'score' => $sentiment_score,
'label' => $sentiment_label,
'positive_count' => $positive_score,
'negative_count' => $negative_score,
'keywords' => $keywords
);
}
/**
* 提取关键词(简单实现)
* @param string $text 文本内容
* @return array 关键词数组
*/
private function extract_keywords($text) {
// 去除标点符号
$text = preg_replace('/[^wx{4e00}-x{9fa5}]+/u', ' ', $text);
// 分词(简单按空格分割,实际应用中应使用分词库)
$words = explode(' ', $text);
// 过滤停用词
$stop_words = array('的', '了', '在', '是', '我', '有', '和', '就', '不', '人', '都', '一', '一个', '上', '也', '很', '到', '说', '要', '去', '你', '会', '着', '没有', '看', '好', '自己', '这');
$filtered_words = array_diff($words, $stop_words);
// 统计词频
$word_counts = array_count_values($filtered_words);
// 按词频排序
arsort($word_counts);
// 取前5个作为关键词
$keywords = array_slice(array_keys($word_counts), 0, 5);
return $keywords;
}
/**
* 批量分析舆情数据
*/
public function batch_analyze() {
global $wpdb;
$table_name = $wpdb->prefix . 'fomr_opinion_data';
// 获取未分析的数据
$unanalyzed_data = $wpdb->get_results(
"SELECT * FROM $table_name WHERE sentiment_score = 0 AND sentiment_label = 'neutral' LIMIT 50"
);
foreach ($unanalyzed_data as $data) {
$analysis_result = $this->analyze($data->content);
// 更新数据库
$wpdb->update(
$table_name,
array(
'sentiment_score' => $analysis_result['score'],
'sentiment_label' => $analysis_result['label'],
'keywords' => implode(',', $analysis_result['keywords'])
),
array('id' => $data->id),
array('%f', '%s', '%s'),
array('%d')
);
}
return count($unanalyzed_data);
}
}
?>
预警系统是舆情监测的关键环节,以下实现一个智能预警类:
<?php
/**
* 舆情预警系统类
* 负责监测舆情变化并触发预警
*/
class FOMR_Alert_System {
private $options;
public function __construct() {
$this->options = get_option('fomr_options');
}
/**
* 检查并触发预警
*/
public function check_alerts() {
global $wpdb;
$table_name = $wpdb->prefix . 'fomr_opinion_data';
// 获取最近24小时的舆情数据
$recent_data = $wpdb->get_results(
$wpdb->prepare(
"SELECT * FROM $table_name
WHERE collected_time >= %s
ORDER BY collected_time DESC",
date('Y-m-d H:i:s', strtotime('-24 hours'))
)
);
$alerts = array();
// 检查负面舆情激增
$negative_surge = $this->check_negative_surge($recent_data);
if ($negative_surge) {
$alerts[] = $negative_surge;
}
// 检查关键词突现
$keyword_emergence = $this->check_keyword_emergence($recent_data);
if ($keyword_emergence) {
$alerts[] = $keyword_emergence;
}
// 检查情感趋势变化
$sentiment_trend = $this->check_sentiment_trend($recent_data);
if ($sentiment_trend) {
$alerts[] = $sentiment_trend;
}
// 如果有预警,发送通知
if (!empty($alerts)) {
$this->send_alerts($alerts);
}
return $alerts;
}
/**
* 检查负面舆情激增
* @param array $data 舆情数据
* @return array|bool 预警信息或false
*/
private function check_negative_surge($data) {
$threshold = isset($this->options['sentiment_threshold']) ?
$this->options['sentiment_threshold'] : 0.7;
$negative_count = 0;
$total_count = count($data);
foreach ($data as $item) {
if ($item->sentiment_label == 'negative' &&
abs($item->sentiment_score) > $threshold) {
$negative_count++;
}
}
if ($total_count > 0) {
$negative_ratio = $negative_count / $total_count;
// 如果负面舆情比例超过30%,触发预警
if ($negative_ratio > 0.3 && $negative_count >= 5) {
return array(
'type' => 'negative_surge',
'level' => $negative_ratio > 0.5 ? 'high' : 'medium',
'message' => sprintf(
'检测到负面舆情激增:最近24小时共%d条舆情,其中%d条为负面(占比%.1f%%)',
$total_count,
$negative_count,
$negative_ratio * 100
),
'data' => array(
'total_count' => $total_count,
'negative_count' => $negative_count,
'ratio' => $negative_ratio
)
);
}
}
return false;
}
/**
* 检查关键词突现
* @param array $data 舆情数据
* @return array|bool 预警信息或false
*/
private function check_keyword_emergence($data) {
$all_keywords = array();
// 收集所有关键词
foreach ($data as $item) {
if (!empty($item->keywords)) {
$keywords = explode(',', $item->keywords);
$all_keywords = array_merge($all_keywords, $keywords);
}
}
// 统计词频
$keyword_counts = array_count_values($all_keywords);
// 找出高频关键词(出现3次以上)
$emerging_keywords = array();
foreach ($keyword_counts as $keyword => $count) {
if ($count >= 3 && strlen($keyword) > 1) {
$emerging_keywords[$keyword] = $count;
}
}
if (!empty($emerging_keywords)) {
arsort($emerging_keywords);
return array(
'type' => 'keyword_emergence',
'level' => 'medium',
'message' => '检测到关键词突现:' . implode('、', array_keys(array_slice($emerging_keywords, 0, 3))),
'data' => $emerging_keywords
);
}
return false;
}
/**
* 检查情感趋势变化
* @param array $data 舆情数据
* @return array|bool 预警信息或false
*/
private function check_sentiment_trend($data) {
if (count($data) < 10) {
return false;
}
// 按时间分组(每4小时一组)
$time_groups = array();
foreach ($data as $item) {
$hour = date('H', strtotime($item->collected_time));
$group = floor($hour / 4);
if (!isset($time_groups[$group])) {
$time_groups[$group] = array(
'count' => 0,
'total_score' => 0
);
}
$time_groups[$group]['count']++;
$time_groups[$group]['total_score'] += $item->sentiment_score;
}
// 计算每组平均情感得分
$averages = array();
foreach ($time_groups as $group => $stats) {
if ($stats['count'] > 0) {
$averages[$group] = $stats['total_score'] / $stats['count'];
}
}
// 检查趋势(最近两组与前两组比较)
if (count($averages) >= 4) {
$recent_avg = array_slice($averages, 0, 2);
$previous_avg = array_slice($averages, 2, 2);
$recent_score = array_sum($recent_avg) / count($recent_avg);
$previous_score = array_sum($previous_avg) / count($previous_avg);
// 如果情感得分下降超过0.5,触发预警
if (($previous_score - $recent_score) > 0.5) {
return array(
'type' => 'sentiment_decline',
'level' => 'medium',
'message' => sprintf(
'检测到情感趋势下降:近期情感得分从%.2f下降至%.2f',
$previous_score,
$recent_score
),
'data' => array(
'previous_score' => $previous_score,
'recent_score' => $recent_score,
'change' => $previous_score - $recent_score
)
);
}
}
return false;
}
/**
* 发送预警通知
* @param array $alerts 预警信息数组
*/
private function send_alerts($alerts) {
$email = isset($this->options['alert_email']) ?
$this->options['alert_email'] : get_option('admin_email');
$subject = '舆情监测系统预警通知';
$message = "<h2>舆情监测系统预警通知</h2>n";
$message .= "<p>检测时间:" . date('Y-m-d H:i:s') . "</p>n";
$message .= "<hr>n";
foreach ($alerts as $index => $alert) {
$level_color = $alert['level'] == 'high' ? 'red' :
($alert['level'] == 'medium' ? 'orange' : 'blue');
$message .= "<div style='border: 1px solid #ccc; padding: 10px; margin: 10px 0;'>n";
$message .= "<h3 style='color: {$level_color};'>预警#" . ($index + 1) . " - " .
$this->get_alert_type_name($alert['type']) . "</h3>n";
$message .= "<p><strong>级别:</strong>" .
($alert['level'] == 'high' ? '高' : ($alert['level'] == 'medium' ? '中' : '低')) . "</p>n";
$message .= "<p><strong>描述:</strong>" . $alert['message'] . "</p>n";
if (!empty($alert['data'])) {
$message .= "<p><strong>详细数据:</strong></p>n";
$message .= "<pre>" . print_r($alert['data'], true) . "</pre>n";
}
$message .= "</div>n";
}
$message .= "<hr>n";
$message .= "<p>请登录<a href='" . admin_url('admin.php?page=fomr-dashboard') . "'>舆情监测系统</a>查看详情。</p>n";
// 发送邮件
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail($email, $subject, $message, $headers);
// 同时记录到系统日志
$this->log_alerts($alerts);
}
/**
* 获取预警类型名称
* @param string $type 预警类型
* @return string 类型名称
*/
private function get_alert_type_name($type) {
$names = array(
'negative_surge' => '负面舆情激增',
'keyword_emergence' => '关键词突现',
'sentiment_decline' => '情感趋势下降'
);
return isset($names[$type]) ? $names[$type] : $type;
}
/**
* 记录预警日志
* @param array $alerts 预警信息
*/
private function log_alerts($alerts) {
global $wpdb;
$table_name = $wpdb->prefix . 'fomr_alert_logs';
foreach ($alerts as $alert) {
$wpdb->insert(
$table_name,
array(
'alert_type' => $alert['type'],
'alert_level' => $alert['level'],
'alert_message' => $alert['message'],
'alert_data' => maybe_serialize($alert['data']),
'created_time' => current_time('mysql')
),
array('%s', '%s', '%s', '%s', '%s')
);
}
}
/**
* 设置定时预警检查
*/
public function schedule_alert_check() {
if (!wp_next_scheduled('fomr_check_alerts_event')) {
wp_schedule_event(time(), 'hourly', 'fomr_check_alerts_event');
}
add_action('fomr_check_alerts_event', array($this, 'check_alerts'));
}
}
?>
响应建议系统帮助编辑快速制定应对策略:
<?php
/**
* 智能响应建议类
* 根据舆情分析结果生成响应建议
*/
class FOMR_Response_Suggestor {
/**
* 生成响应建议
* @param int $data_id 舆情数据ID
* @return array 响应建议
*/
public function generate_suggestions($data_id) {
global $wpdb;
$table_name = $wpdb->prefix . 'fomr_opinion_data';
// 获取舆情数据
$data = $wpdb->get_row($wpdb->prepare(
"SELECT * FROM $table_name WHERE id = %d",
$data_id
));
if (!$data) {
return array('error' => '数据不存在');
}
$suggestions = array();
// 根据情感标签生成建议
switch ($data->sentiment_label) {
case 'positive':
$suggestions = $this->suggest_for_positive($data);
break;
case 'negative':
$suggestions = $this->suggest_for_negative($data);
break;
case 'neutral':
$suggestions = $this->suggest_for_neutral($data);
break;
}
// 根据来源生成额外建议
$source_suggestions = $this->suggest_by_source($data);
$suggestions = array_merge($suggestions, $source_suggestions);
// 保存建议到数据库
$this->save_suggestions($data_id, $suggestions);
return $suggestions;
}
/**
* 针对正面舆情的建议
* @param object $data 舆情数据
* @return array 建议数组
*/
private function suggest_for_positive($data) {
$suggestions = array();
// 根据情感得分调整建议强度
$strength = $data->sentiment_score > 0.7 ? 'strong' : 'moderate';
$suggestions[] = array(
'type' => 'amplify',
'title' => '放大正面声音',
'content' => $this->get_amplify_suggestion($data, $strength),
'priority' => 1
);
$suggestions[] = array(
'type' => 'engage',
'title' => '加强用户互动',
'content' => '在相关平台回复感谢用户,邀请分享更多正面体验',
'priority' => 2
);
if ($strength == 'strong') {
$suggestions[] = array(
'type' => 'leverage',
'title' => '利用口碑传播',
'content' => '考虑将用户正面评价用于宣传材料,制作案例分享',
'priority' => 3
);
}
return $suggestions;
}
/**
* 针对负面舆情的建议
* @param object $data 舆情数据
* @return array 建议数组
*/
private function suggest_for_negative($data) {
$suggestions = array();
$severity = abs($data->sentiment_score) > 0.7 ? 'severe' : 'moderate';
$suggestions[] = array(
'type' => 'respond',
'title' => '及时响应',
'content' => $this->get_response_suggestion($data, $severity),
'priority' => 1,
'urgency' => $severity == 'severe' ? 'high' : 'medium'
);
$suggestions[] = array(
'type' => 'investigate',
'title' => '问题调查',
'content' => '检查是否系统性问题,收集更多用户反馈',
'priority' => 2,
'urgency' => 'medium'
);
if ($severity == 'severe') {
$suggestions[] = array(
'type' => 'escalate',
'title' => '升级处理',
'content' => '通知相关部门负责人,制定专项解决方案',
'priority' => 1,
'urgency' => 'high'
);
}
return $suggestions;
}
/**
* 针对中性舆情的建议
* @param object $data 舆情数据
* @return array 建议数组
*/
private function suggest_for_neutral($data) {
return array(
array(
'type' => 'monitor',
'title' => '持续监测',
'content' => '保持关注,观察舆情发展趋势',
'priority' => 3,
'urgency' => 'low'
),
array(
'type' => 'engage',
'title' => '引导讨论',
'content' => '可以主动发起相关话题讨论,引导用户表达观点',
'priority' => 2,
'urgency' => 'low'
)
);
}
/**
* 根据数据来源生成建议
* @param object $data 舆情数据
* @return array 建议数组
*/
private function suggest_by_source($data) {
$suggestions = array();
switch ($data->source) {
case 'weibo':
$suggestions[] = array(
'type' => 'platform_specific',
'title' => '微博平台策略',
'content' => '考虑使用微博的转发、话题功能扩大影响',
'priority' => 2
);
break;
case 'weixin':
$suggestions[] = array(
'type' => 'platform_specific',
'title' => '微信平台策略',
'content' => '可通过公众号文章或朋友圈进行深度沟通',
'priority' => 2
);
break;
case 'news':
$suggestions[] = array(
'type' => 'platform_specific',
'title' => '新闻媒体策略',
'content' => '考虑准备新闻稿或媒体声明',
'priority' => 2
);
break;
}
return $suggestions;
}
/**
* 获取放大建议的具体内容
* @param object $data 舆情数据
* @param string $strength 强度
* @return string 建议内容
*/
private function get_amplify_suggestion($data, $strength) {
$templates = array(
'strong' => '该正面评价情感强烈(得分%.2f),建议重点推广。可联系用户获取详细使用体验,制作成案例研究。',
'moderate' => '该正面评价情感积极(得分%.2f),可进行常规推广。在相关渠道分享用户好评,增强品牌信誉。'
);
return sprintf(
$templates[$strength],
$data->sentiment_score
);


