從零開始構建微博爬蟲與數據分析系統

從零開始構建微博爬蟲與數據分析系統

引言

社交媒體平臺蘊含著海量的信息和數據,通過對這些數據的收集和分析,我們可以挖掘出有價值的見解。本文將詳細介紹如何構建一個完整的微博爬蟲和數據分析系統,從數據爬取、清洗、到多維度分析與可視化。

系統架構

整個系統分為兩個主要模塊:

  1. 微博爬蟲模塊:負責通過API獲取微博數據并保存
  2. 數據分析模塊:對獲取的數據進行清洗和多維度分析

一、微博爬蟲實現

1.1 爬蟲設計思路

微博的數據爬取主要基于其Ajax接口,通過模擬瀏覽器請求獲取JSON格式數據。主要挑戰在于:

  • 需要登錄憑證(Cookie)才能訪問完整內容
  • 接口限制和反爬措施
  • 數據格式的解析與清洗

1.2 核心代碼實現

WeiboCrawler類是爬蟲的核心,主要包含以下功能:

class WeiboCrawler:def __init__(self, cookie=None):# 初始化請求頭和會話self.headers = {...}if cookie:self.headers['Cookie'] = cookieself.session = requests.Session()self.session.headers.update(self.headers)def get_user_info(self, user_id):# 獲取用戶基本信息url = f'https://weibo.com/ajax/profile/info?uid={user_id}'# 實現...def get_user_weibos(self, user_id, page=1, count=20):# 獲取用戶微博列表url = f'https://weibo.com/ajax/statuses/mymblog?uid={user_id}&page={page}&feature=0'# 實現...def crawl_user_weibos(self, user_id, max_pages=None):# 爬取所有微博并返回結果# 實現...

1.3 數據清洗與存儲

爬取的原始數據需要進行清洗,主要包括:

  • 去除HTML標簽和特殊字符
  • 提取時間、內容、圖片鏈接等信息
  • 識別轉發內容并單獨處理

清洗后的數據以結構化文本形式存儲,便于后續分析:

def format_weibo(self, weibo):# 格式化微博內容為易讀格式created_at = datetime.strptime(weibo['created_at'], '%a %b %d %H:%M:%S %z %Y')text = self.clean_text(weibo.get('text', ''))formatted = f"[{created_at.strftime('%Y-%m-%d %H:%M:%S')}]\n{text}\n"# 處理轉發內容、圖片鏈接等# ...return formatted

二、數據分析模塊

2.1 數據加載與預處理

WeiboAnalyzer類負責從文本文件加載微博數據,并轉換為結構化形式:

def load_data(self):# 從文件加載微博數據with open(self.file_path, 'r', encoding='utf-8') as f:lines = f.readlines()# 提取用戶信息和微博內容# ...print(f"成功加載 {len(self.weibos)} 條微博")

2.2 時間分布分析

分析微博發布的時間規律,包括日期、小時和星期分布:

def time_distribution_analysis(self):# 提取日期和時間dates = [weibo['date'].date() for weibo in self.weibos]hours = [weibo['date'].hour for weibo in self.weibos]weekdays = [weibo['date'].weekday() for weibo in self.weibos]# 使用pandas和matplotlib進行統計和可視化# ...

通過這一分析,我們可以了解用戶在什么時間段最活躍,是否有固定的發布模式。

2.3 內容分析與關鍵詞提取

使用jieba分詞和TF-IDF算法提取微博內容的關鍵詞:

def content_analysis(self):# 合并所有微博內容all_content = ' '.join([weibo['content'] for weibo in self.weibos])# 使用jieba進行分詞jieba.analyse.set_stop_words('stopwords.txt')words = jieba.cut(all_content)# 過濾單個字符和數字filtered_words = [word for word in words if len(word) > 1 and not word.isdigit()]# 統計詞頻word_counts = Counter(filtered_words)# 提取關鍵詞keywords = jieba.analyse.extract_tags(all_content, topK=50, withWeight=True)# 生成詞云和關鍵詞圖表# ...

詞云能直觀地展示內容主題,關鍵詞分析則揭示了用戶最關注的話題。

2.4 引用人物分析

分析微博中引用的名人或專家:

def quote_analysis(self):# 定義可能被引用的人物列表famous_people = ['曾國藩', '尼采', '榮格', '蘇格拉底', '馬云', '武志紅', '阿德勒', '王安石', '蘇東坡', '海德格爾', '左宗棠', '宗薩']# 統計每個人物被引用的次數quotes = {person: 0 for person in famous_people}for weibo in self.weibos:content = weibo['content']for person in famous_people:if person in content:quotes[person] += 1# 繪制引用人物條形圖# ...

這一分析可以揭示用戶的思想傾向和崇拜的對象。

2.5 圖片使用分析

分析微博中的圖片使用情況:

def image_analysis(self):# 統計帶圖片的微博數量weibos_with_images = [weibo for weibo in self.weibos if weibo['images']]image_counts = [len(weibo['images']) for weibo in weibos_with_images]# 計算統計數據total_weibos = len(self.weibos)weibos_with_images_count = len(weibos_with_images)percentage = weibos_with_images_count / total_weibos * 100 if total_weibos > 0 else 0# 繪制餅圖和分布圖# ...

三、可視化報告生成

最終,將所有分析結果整合為一個HTML報告:

def generate_report(self):# 執行所有分析self.time_distribution_analysis()self.content_analysis()self.quote_analysis()self.image_analysis()# 生成HTML報告html_content = f"""<!DOCTYPE html><html><head><meta charset="UTF-8"><title>微博數據分析報告</title><style>body {{ font-family: Arial, sans-serif; margin: 20px; }}h1, h2 {{ color: #1DA1F2; }}.section {{ margin-bottom: 30px; }}img {{ max-width: 100%; border: 1px solid #ddd; }}</style></head><body><h1>微博數據分析報告</h1><!-- 各部分分析結果 --><!-- ... --></body></html>"""with open('weibo_analysis_report.html', 'w', encoding='utf-8') as f:f.write(html_content)

四、實際應用案例

以用戶"侯小強"(ID: 1004524612)為例,我爬取了其全部1069條微博并進行分析。以下是一些關鍵發現:

  1. 時間分布:該用戶主要在晚上8點至10點發布微博,周六和周日活躍度明顯高于工作日
  2. 關鍵詞分析:心理、生活、思考是最常出現的關鍵詞,表明用戶關注心理學和個人成長話題
  3. 引用分析:尼采、榮格、蘇格拉底是被最多引用的人物,表明用戶對西方哲學有較深興趣
  4. 圖片使用:約37%的微博包含圖片,其中以單圖發布為主

網頁展示效果如下:
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述

在這里插入圖片描述

五、技術難點與解決方案

  1. 反爬蟲機制:微博有嚴格的請求頻率限制,我通過設置合理的請求間隔(1秒)和會話保持來解決
  2. 中文分詞挑戰:中文分詞準確度對內容分析至關重要,使用jieba庫并自定義停用詞表提高分析質量
  3. 數據清洗:微博內容中包含大量HTML標簽和特殊字符,需要精心設計正則表達式進行清洗
  4. 可視化定制:調整matplotlib的中文字體和樣式設置,確保圖表美觀且信息豐富

六、總結與展望

本項目實現了一個完整的微博數據爬取和分析系統,可以幫助我們從用戶的微博內容中挖掘出有價值的信息。未來的改進方向包括:

  1. 支持多用戶批量爬取和對比分析
  2. 加入情感分析功能,評估微博的情感傾向
  3. 增加互動數據(點贊、評論、轉發)的分析
  4. 開發時間序列分析,檢測用戶興趣變化趨勢

通過這個項目,我們不僅可以了解特定用戶的發布規律和內容偏好,還能窺探社交媒體用戶的思想動態和關注重點,為社會學和心理學研究提供數據支持。
完整代碼:爬取數據代碼-weibo_crawler.py

import requests
import json
import time
import os
import re
import argparse
from datetime import datetimeclass WeiboCrawler:def __init__(self, cookie=None):"""初始化微博爬蟲:param cookie: 用戶登錄的cookie字符串"""self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36','Accept': 'application/json, text/plain, */*','Accept-Language': 'zh-CN,zh;q=0.9','Referer': 'https://weibo.com/','Origin': 'https://weibo.com',}if cookie:self.headers['Cookie'] = cookieself.session = requests.Session()self.session.headers.update(self.headers)def get_user_info(self, user_id):"""獲取用戶基本信息:param user_id: 用戶ID:return: 用戶信息字典"""url = f'https://weibo.com/ajax/profile/info?uid={user_id}'try:response = self.session.get(url)if response.status_code == 200:data = response.json()if data.get('ok') == 1 and 'data' in data:return data['data']['user']return Noneexcept Exception as e:print(f"獲取用戶信息失敗: {e}")return Nonedef get_user_weibos(self, user_id, page=1, count=20):"""獲取用戶的微博列表:param user_id: 用戶ID:param page: 頁碼:param count: 每頁微博數量:return: 微博列表"""url = f'https://weibo.com/ajax/statuses/mymblog?uid={user_id}&page={page}&feature=0'try:response = self.session.get(url)if response.status_code == 200:data = response.json()if data.get('ok') == 1 and 'data' in data:return data['data']['list'], data['data']['total']return [], 0except Exception as e:print(f"獲取微博列表失敗: {e}")return [], 0def clean_text(self, text):"""清理文本內容,去除HTML標簽等:param text: 原始文本:return: 清理后的文本"""if not text:return ""# 去除HTML標簽text = re.sub(r'<[^>]+>', '', text)# 替換特殊字符text = text.replace('&nbsp;', ' ')text = text.replace('&lt;', '<')text = text.replace('&gt;', '>')text = text.replace('&amp;', '&')# 去除多余空格和換行text = re.sub(r'\s+', ' ', text).strip()return textdef format_weibo(self, weibo):"""格式化微博內容:param weibo: 微博數據:return: 格式化后的微博文本"""created_at = datetime.strptime(weibo['created_at'], '%a %b %d %H:%M:%S %z %Y').strftime('%Y-%m-%d %H:%M:%S')text = self.clean_text(weibo.get('text', ''))formatted = f"[{created_at}]\n"formatted += f"{text}\n"# 添加轉發內容if 'retweeted_status' in weibo and weibo['retweeted_status']:retweeted = weibo['retweeted_status']retweeted_user = retweeted.get('user', {}).get('screen_name', '未知用戶')retweeted_text = self.clean_text(retweeted.get('text', ''))formatted += f"\n轉發 @{retweeted_user}: {retweeted_text}\n"# 添加圖片鏈接if 'pic_ids' in weibo and weibo['pic_ids']:formatted += "\n圖片鏈接:\n"for pic_id in weibo['pic_ids']:pic_url = f"https://wx1.sinaimg.cn/large/{pic_id}.jpg"formatted += f"{pic_url}\n"formatted += "-" * 50 + "\n"return formatteddef crawl_user_weibos(self, user_id, max_pages=None):"""爬取用戶的所有微博:param user_id: 用戶ID:param max_pages: 最大爬取頁數,None表示爬取全部:return: 所有微博內容的列表"""user_info = self.get_user_info(user_id)if not user_info:print(f"未找到用戶 {user_id} 的信息")return []screen_name = user_info.get('screen_name', user_id)print(f"開始爬取用戶 {screen_name} 的微博")all_weibos = []page = 1total_pages = float('inf')while (max_pages is None or page <= max_pages) and page <= total_pages:print(f"正在爬取第 {page} 頁...")weibos, total = self.get_user_weibos(user_id, page)if not weibos:breakall_weibos.extend(weibos)# 計算總頁數if total > 0:total_pages = (total + 19) // 20  # 每頁20條,向上取整page += 1# 防止請求過快time.sleep(1)print(f"共爬取到 {len(all_weibos)} 條微博")return all_weibos, screen_namedef save_weibos_to_file(self, user_id, max_pages=None):"""爬取用戶微博并保存到文件:param user_id: 用戶ID:param max_pages: 最大爬取頁數:return: 保存的文件路徑"""weibos, screen_name = self.crawl_user_weibos(user_id, max_pages)if not weibos:return None# 創建文件名filename = f"{user_id}_weibos.txt"# 寫入文件with open(filename, 'w', encoding='utf-8') as f:f.write(f"用戶: {screen_name} (ID: {user_id})\n")f.write(f"爬取時間: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")f.write(f"微博數量: {len(weibos)}\n")f.write("=" * 50 + "\n\n")for weibo in weibos:formatted = self.format_weibo(weibo)f.write(formatted)print(f"微博內容已保存到文件: {filename}")return filenamedef main():parser = argparse.ArgumentParser(description='微博爬蟲 - 爬取指定用戶的微博')parser.add_argument('user_id', help='微博用戶ID')parser.add_argument('--cookie', help='登錄cookie字符串', default=None)parser.add_argument('--max-pages', type=int, help='最大爬取頁數', default=None)parser.add_argument('--cookie-file', help='包含cookie的文件路徑', default=None)args = parser.parse_args()cookie = args.cookie# 如果提供了cookie文件,從文件讀取cookieif args.cookie_file and not cookie:try:with open(args.cookie_file, 'r', encoding='utf-8') as f:cookie = f.read().strip()except Exception as e:print(f"讀取cookie文件失敗: {e}")crawler = WeiboCrawler(cookie=cookie)crawler.save_weibos_to_file(args.user_id, args.max_pages)if __name__ == "__main__":main()

數據分析代碼:weibo_analsis.py

import re
import os
import matplotlib.pyplot as plt
from datetime import datetime
import jieba
import jieba.analyse
from collections import Counter
import numpy as np
from wordcloud import WordCloud
import matplotlib.font_manager as fm
from matplotlib.font_manager import FontProperties
import pandas as pd
from matplotlib.dates import DateFormatter
import seaborn as sns# 設置中文字體
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用來正常顯示中文標簽
plt.rcParams['axes.unicode_minus'] = False  # 用來正常顯示負號class WeiboAnalyzer:def __init__(self, file_path):"""初始化微博分析器:param file_path: 微博數據文件路徑"""self.file_path = file_pathself.weibos = []self.user_info = {}self.load_data()def load_data(self):"""加載微博數據"""with open(self.file_path, 'r', encoding='utf-8') as f:lines = f.readlines()# 提取用戶信息if lines and "用戶:" in lines[0]:user_info_match = re.match(r'用戶: (.*) \(ID: (.*)\)', lines[0])if user_info_match:self.user_info['name'] = user_info_match.group(1)self.user_info['id'] = user_info_match.group(2)if len(lines) > 2 and "微博數量:" in lines[2]:count_match = re.match(r'微博數量: (\d+)', lines[2])if count_match:self.user_info['count'] = int(count_match.group(1))# 提取微博內容current_weibo = Nonefor line in lines:# 新微博的開始if re.match(r'\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\]', line):if current_weibo:self.weibos.append(current_weibo)date_match = re.match(r'\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\]', line)if date_match:date_str = date_match.group(1)content = line[len(date_str) + 3:].strip()current_weibo = {'date': datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S'),'content': content,'images': [],'is_retweet': False,'retweet_content': '','retweet_user': ''}# 圖片鏈接elif line.strip().startswith('https://wx1.sinaimg.cn/'):if current_weibo:current_weibo['images'].append(line.strip())# 轉發內容elif current_weibo and line.strip().startswith('轉發 @'):current_weibo['is_retweet'] = Trueretweet_match = re.match(r'轉發 @(.*): (.*)', line.strip())if retweet_match:current_weibo['retweet_user'] = retweet_match.group(1)current_weibo['retweet_content'] = retweet_match.group(2)# 繼續添加內容elif current_weibo and not line.strip() == '-' * 50 and not line.strip() == '=' * 50:current_weibo['content'] += ' ' + line.strip()# 添加最后一條微博if current_weibo:self.weibos.append(current_weibo)print(f"成功加載 {len(self.weibos)} 條微博")def time_distribution_analysis(self):"""分析微博發布時間分布"""if not self.weibos:print("沒有微博數據可分析")return# 提取日期和時間dates = [weibo['date'].date() for weibo in self.weibos]hours = [weibo['date'].hour for weibo in self.weibos]weekdays = [weibo['date'].weekday() for weibo in self.weibos]# 創建日期DataFramedf = pd.DataFrame({'date': dates,'hour': hours,'weekday': weekdays})# 按日期統計date_counts = df['date'].value_counts().sort_index()# 按小時統計hour_counts = df['hour'].value_counts().sort_index()# 按星期幾統計weekday_counts = df['weekday'].value_counts().sort_index()weekday_names = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']# 創建圖表fig, axes = plt.subplots(3, 1, figsize=(12, 15))# 日期分布圖axes[0].plot(date_counts.index, date_counts.values, marker='o')axes[0].set_title('微博發布日期分布')axes[0].set_xlabel('日期')axes[0].set_ylabel('微博數量')axes[0].grid(True)# 小時分布圖axes[1].bar(hour_counts.index, hour_counts.values)axes[1].set_title('微博發布時間段分布')axes[1].set_xlabel('小時')axes[1].set_ylabel('微博數量')axes[1].set_xticks(range(0, 24))axes[1].grid(True)# 星期幾分布圖axes[2].bar([weekday_names[i] for i in weekday_counts.index], weekday_counts.values)axes[2].set_title('微博發布星期分布')axes[2].set_xlabel('星期')axes[2].set_ylabel('微博數量')axes[2].grid(True)plt.tight_layout()plt.savefig('time_distribution.png')plt.close()print("時間分布分析完成,結果已保存為 time_distribution.png")def content_analysis(self):"""分析微博內容"""if not self.weibos:print("沒有微博數據可分析")return# 合并所有微博內容all_content = ' '.join([weibo['content'] for weibo in self.weibos])# 使用jieba進行分詞jieba.analyse.set_stop_words('stopwords.txt')  # 如果有停用詞表words = jieba.cut(all_content)# 過濾掉單個字符和數字filtered_words = [word for word in words if len(word) > 1 and not word.isdigit()]# 統計詞頻word_counts = Counter(filtered_words)# 提取關鍵詞keywords = jieba.analyse.extract_tags(all_content, topK=50, withWeight=True)# 創建詞云wordcloud = WordCloud(font_path='simhei.ttf',  # 設置中文字體width=800,height=400,background_color='white').generate_from_frequencies(dict(word_counts))# 繪制詞云圖plt.figure(figsize=(10, 6))plt.imshow(wordcloud, interpolation='bilinear')plt.axis('off')plt.title('微博內容詞云')plt.savefig('wordcloud.png')plt.close()# 繪制關鍵詞條形圖plt.figure(figsize=(12, 8))keywords_dict = dict(keywords[:20])plt.barh(list(reversed(list(keywords_dict.keys()))), list(reversed(list(keywords_dict.values()))))plt.title('微博內容關鍵詞TOP20')plt.xlabel('權重')plt.tight_layout()plt.savefig('keywords.png')plt.close()print("內容分析完成,結果已保存為 wordcloud.png 和 keywords.png")def quote_analysis(self):"""分析微博中引用的人物"""if not self.weibos:print("沒有微博數據可分析")return# 定義可能被引用的人物列表famous_people = ['曾國藩', '尼采', '榮格', '蘇格拉底', '馬云', '武志紅', '阿德勒', '王安石', '蘇東坡', '海德格爾', '左宗棠', '宗薩']# 統計每個人物被引用的次數quotes = {person: 0 for person in famous_people}for weibo in self.weibos:content = weibo['content']for person in famous_people:if person in content:quotes[person] += 1# 過濾掉未被引用的人物quotes = {k: v for k, v in quotes.items() if v > 0}# 按引用次數排序sorted_quotes = dict(sorted(quotes.items(), key=lambda item: item[1], reverse=True))# 繪制引用人物條形圖plt.figure(figsize=(10, 6))plt.bar(sorted_quotes.keys(), sorted_quotes.values())plt.title('微博中引用人物統計')plt.xlabel('人物')plt.ylabel('引用次數')plt.xticks(rotation=45)plt.tight_layout()plt.savefig('quotes.png')plt.close()print("引用人物分析完成,結果已保存為 quotes.png")def image_analysis(self):"""分析微博中的圖片使用情況"""if not self.weibos:print("沒有微博數據可分析")return# 統計帶圖片的微博數量weibos_with_images = [weibo for weibo in self.weibos if weibo['images']]image_counts = [len(weibo['images']) for weibo in weibos_with_images]# 計算統計數據total_weibos = len(self.weibos)weibos_with_images_count = len(weibos_with_images)percentage = weibos_with_images_count / total_weibos * 100 if total_weibos > 0 else 0# 繪制餅圖plt.figure(figsize=(8, 8))plt.pie([weibos_with_images_count, total_weibos - weibos_with_images_count], labels=['帶圖片微博', '純文字微博'], autopct='%1.1f%%',startangle=90)plt.title('微博圖片使用情況')plt.axis('equal')plt.savefig('image_usage.png')plt.close()# 繪制圖片數量分布if image_counts:plt.figure(figsize=(10, 6))counter = Counter(image_counts)plt.bar(counter.keys(), counter.values())plt.title('微博圖片數量分布')plt.xlabel('圖片數量')plt.ylabel('微博數量')plt.xticks(range(1, max(image_counts) + 1))plt.grid(axis='y')plt.savefig('image_count.png')plt.close()print("圖片使用分析完成,結果已保存為 image_usage.png 和 image_count.png")def generate_report(self):"""生成分析報告"""# 執行所有分析self.time_distribution_analysis()self.content_analysis()self.quote_analysis()self.image_analysis()# 生成HTML報告html_content = f"""<!DOCTYPE html><html><head><meta charset="UTF-8"><title>微博數據分析報告</title><style>body {{ font-family: Arial, sans-serif; margin: 20px; }}h1, h2 {{ color: #1DA1F2; }}.section {{ margin-bottom: 30px; }}img {{ max-width: 100%; border: 1px solid #ddd; }}</style></head><body><h1>微博數據分析報告</h1><div class="section"><h2>用戶信息</h2><p>用戶名: {self.user_info.get('name', '未知')}</p><p>用戶ID: {self.user_info.get('id', '未知')}</p><p>微博總數: {self.user_info.get('count', len(self.weibos))}</p><p>分析微博數: {len(self.weibos)}</p></div><div class="section"><h2>時間分布分析</h2><img src="time_distribution.png" alt="時間分布分析"></div><div class="section"><h2>內容分析</h2><h3>詞云</h3><img src="wordcloud.png" alt="詞云"><h3>關鍵詞</h3><img src="keywords.png" alt="關鍵詞"></div><div class="section"><h2>引用人物分析</h2><img src="quotes.png" alt="引用人物分析"></div><div class="section"><h2>圖片使用分析</h2><img src="image_usage.png" alt="圖片使用情況"><img src="image_count.png" alt="圖片數量分布"></div></body></html>"""with open('weibo_analysis_report.html', 'w', encoding='utf-8') as f:f.write(html_content)print("分析報告已生成: weibo_analysis_report.html")def main():# 創建停用詞文件(如果需要)stopwords = ['的', '了', '在', '是', '我', '有', '和', '就', '不', '人', '都', '一', '一個', '上', '也', '很', '到', '說', '要', '去', '你', '會', '著', '沒有', '看', '好', '自己', '這', '那', '啊', '吧', '把', '給', '但是', '但', '還', '可以', '這個', '這樣', '這些', '因為', '所以', '如果', '就是', '么', '什么', '只是', '只有', '這種', '那個', '他們']with open('stopwords.txt', 'w', encoding='utf-8') as f:f.write('\n'.join(stopwords))# 分析微博數據analyzer = WeiboAnalyzer('1004524612_weibos.txt')analyzer.generate_report()if __name__ == "__main__":main()

所有數據以及代碼也放在下面的倉庫里了:源碼鏈接

參考資料

  1. Python爬蟲實戰指南
  2. 《數據可視化之美》
  3. 自然語言處理與文本挖掘技術
  4. jieba中文分詞官方文檔

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/77722.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/77722.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/77722.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

深入探索RAG:用LlamaIndex為大語言模型擴展知識,實現智能檢索增強生成

大型語言模型&#xff08;LLM&#xff09;&#xff0c;如ChatGPT和Llama&#xff0c;在回答問題方面表現出色&#xff0c;但它們的知識僅限于訓練時所獲取的信息。它們無法訪問私有數據&#xff0c;也無法在訓練截止日期之后學習新知識。那么&#xff0c;核心問題就是……我們如…

【延遲雙刪】簡單解析

使用場景&#xff1a;【高并發】情況下的做【更新操作】 什么是延遲雙刪 首次刪除&#xff1a;當需要更新某個數據項時&#xff0c;首先刪除緩存中的該項。 更新數據庫&#xff1a;接著&#xff0c;更新數據庫中的該項。 短暫延遲&#xff1a;然后等待一段很短的時間&#xff…

解決Windows安全中心顯示空白頁面

1、電腦重裝系統后&#xff0c;發現原本一些軟件打不開了&#xff0c;電腦莫名認為有病毒&#xff0c;自動刪除插件。附圖。 2、第一反應是電腦防火墻的原因&#xff0c;默認威脅防護識別到了病毒軟件&#xff0c;自動刪除。在開始屏幕搜Windows安全中心&#xff0c;打開之后發…

【回眸】error: failed to compile `xxxxxx`重裝rust環境

在ubuntu上安裝軟件報錯 error: failed to compile cxx2flow v0.6.2 Caused by: package cargo-platform v0.1.9 cannot be built because it requires rustc 1.78 or newer, while the currently active rustc version is 1.75.0 Try re-running cargo install with --lo…

算法—冒泡排序—js(教學示例、小數據)

冒泡排序原理 冒泡排序是一種簡單的排序算法&#xff0c;通過重復遍歷數組&#xff0c;比較相鄰元素并交換位置&#xff0c;使較大的元素逐漸“浮”到數組末尾。 特點 時間復雜度&#xff1a;平均 O(n)&#xff0c;最優&#xff08;已有序時&#xff09;O(n) 空間復雜度&#…

linux sysfs的使用

在Linux內核驅動開發中&#xff0c;device_create_file 和 device_remove_file 用于動態創建/刪除設備的 sysfs 屬性文件&#xff0c;常用于暴露設備信息或控制參數。以下是完整示例及詳細說明&#xff1a; 1. 頭文件引入 #include <linux/module.h> #include <linux/…

利用 Deepseek 和 Mermaid 畫流程圖

提示詞 你是一個產品經理&#xff0c;請繪制一個報名比賽的流程圖&#xff0c;要求生成符合Mermaid語法的代碼&#xff0c;具體要求如下&#xff1a; 1.注冊賬號 2.填寫報名信息 3.參加比賽 4.查看比賽結果 生成的結果 flowchart TDA([開始]) --> B[注冊賬號]B --> C{賬…

【圖像標注技巧】目標檢測圖像標注技巧

介紹一些圖像標注技巧。之前引用過別人的文章 yolo目標檢測 技巧 trick 提升模型性能&#xff0c;deep research檢測調研報告也可以進行參考。 拉框類的標注&#xff0c;如果你不確定哪種方法好&#xff0c;你可以把所標注區域的都剪切出來&#xff0c;然后站在屏幕一米之外瞇…

數字信號處理技術架構與功能演進

數字信號處理&#xff08;DSP&#xff09;是通過數字運算實現信號分析、變換、濾波及調制解調的技術領域&#xff0c;其發展過程與技術應用如下&#xff1a; 一、定義與核心功能 技術定義&#xff1a;通過算法將模擬信號轉換為數字形式進行處理&#xff0c;具有高精度、可編程…

瀏覽器上下文通信

文章目錄 瀏覽器上下文通信同源通信同源通信流程同一瀏覽器上下文通信不同瀏覽器上下文通信 跨域通信前端和前端跨域前端和后端跨域 瀏覽器上下文通信 瀏覽器上下文通信分為兩種&#xff1a;同源和跨源。同樣的同源通信也分為同一瀏覽器上下文和不同的瀏覽器上下文。 同源通信…

Linux 離線部署 Docker 18.06.3 終極指南(附一鍵安裝卸載腳本)

Linux 離線部署 Docker 18.06.3 終極指南&#xff08;附一鍵安裝/卸載腳本&#xff09; 摘要&#xff1a;本文針對無外網環境的 Linux 服務器&#xff0c;提供基于二進制包的 Docker 18.06.3 離線安裝全流程指南。包含自動化腳本設計、服務配置優化及安全卸載方案&#xff0c;…

【前端】跟著maxkb學習logicflow流程圖畫法

文章目錄 背景1. 選定學習對象-maxkb應用邏輯編排2. 確定實現框架3. 關鍵邏輯&#xff1a;查看app-node.js4. 學習開始節點繪制流程數據形式 5. 給節點增加表單輸入框遇到過的問題 背景 看看前端如何繪制流程圖&#xff0c;界面好看點。 "logicflow/core": "1.…

Android 12系統靜態壁紙深度定制指南

1. 需求背景與實現原理 在Android 12系統ROM定制開發中&#xff0c;擴展靜態壁紙功能需要深入理解WallpaperManagerService的架構體系。系統壁紙管理通過雙端協作實現&#xff1a; WallpaperManagerService&#xff08;frameworks層&#xff09;&#xff1a;負責壁紙狀態管理、…

相得益彰 — 基于 GraphRAG 事理圖譜驅動的實時金融行情新聞資訊洞察

*本文為亞馬遜云科技博客文章&#xff0c;僅用于技術分享&#xff0c;不構成投資建議或金融決策支持。文中涉及的公司名稱僅用于技術示例&#xff0c;不代表亞馬遜云科技觀點或與這些公司的商業合作關系。 背景介紹 在當今這個信息爆炸的時代&#xff0c;金融市場每天都在產生…

OpenCV---圖像預處理(四)

OpenCV—圖像預處理&#xff08;四&#xff09; 文章目錄 OpenCV---圖像預處理&#xff08;四&#xff09;九&#xff0c;圖像掩膜9.1 制作掩膜9.2 與運算9.3 顏色替換9.3.19.3.2 顏色替換 十&#xff0c;ROI切割十 一&#xff0c;圖像添加水印11.1模板輸入11.2 與運算11.3 圖像…

【MySQL】:數據庫事務管理

一&#xff1a;學習路徑 &#xff08;1&#xff09;下載安裝mysql &#xff08;2&#xff09;學習語言&#xff1a;SQL(操作數據庫&#xff09; &#xff08;3&#xff09;mysql集群&#xff08;提升數據庫存儲效率&#xff09; &#xff08;4&#xff09;SQL使用&#xff0c;M…

內存函數和動態內存管理

目錄 一、memcpy庫函數介紹 1. memcpy的使用 2. memcpy的模擬 二、memmove庫函數介紹 1. memmove的使用 2. memmove的模擬 三、memset庫函數介紹 四、memcmp庫函數介紹 五、動態內存中malloc和free 1. malloc 2. free 六、動態內存中calloc和realloc 1. calloc 2. realloc 七、…

yarn的基本介紹

1.Hadoop的三大結構及各自的作用&#xff1a; Hadoop是一個開源的分布式計算框架&#xff0c;它主要包括三大核心組件&#xff1a;HDFS&#xff08;Hadoop Distributed File System&#xff09;、YARN&#xff08;Yet Another Resource Negotiator&#xff09;和MapReduce。以…

STM32的啟動方式

目錄 一、從主閃存存儲器啟動&#xff08;Main Flash Memory&#xff09; 二、從系統存儲器啟動&#xff08;System Memory&#xff09; 三、從內置SRAM啟動&#xff08;Embedded SRAM&#xff09; 四、從外掛存儲介質啟動的實現方式 1. 存儲介質選型 2. 硬件連接 3. 引…

STC定時器頻率占空比程序

// // 一、宏定義區 // #include <STC15.H> //頭文件 #include <intrins.h> //庫函數文件 #define FOSC 12000000L //IRC頻率 typedef …