概述
pytrends 函式庫中的 get_historical_interest() 函數允許您擷取特定搜尋詞在指定時間範圍內的每小時興趣資料。這有助於更細緻地了解搜尋詞的受歡迎程度,並識別在查看每日或每週資料時可能不明顯的趨勢。
在本教學中,我們將介紹:
- 匯入必要的函式庫
- 設定
pytrends請求 - 擷取歷史每小時興趣資料
- 視覺化結果
安裝
要安裝 Pytrends,只需使用 pip:
pip install matplotlib
擷取歷史每小時興趣資料
首先,我們需要匯入必要的函式庫並設定 pytrends 請求。
from pytrends.request import TrendReq
import pandas as pd
import matplotlib.pyplot as plt
# Set up pytrends request
pytrends = TrendReq(hl='en-US', tz=360)
接下來,我們將使用 get_historical_interest() 函數指定搜尋詞、時間範圍和其他請求參數。
keywords = ['Python', 'JavaScript']
# Retrieve hourly interest data
hourly_interest = pytrends.get_historical_interest(keywords, year_start=2023, month_start=3, day_start=1, hour_start=0, year_end=2023, month_end=3, day_end=2, hour_end=0, cat=0, geo='', gprop='', sleep=0)
這將返回一個 DataFrame,其中包含搜尋詞「Python」和「JavaScript」從 2023 年 3 月 1 日到 3 月 2 日的每小時興趣資料。
視覺化結果
現在,我們可以使用簡單的折線圖來視覺化每小時興趣資料。
# Plot the hourly interest data
plt.figure(figsize=(12, 6))
plt.plot(hourly_interest.index, hourly_interest['Python'], label='Python')
plt.plot(hourly_interest.index, hourly_interest['JavaScript'], label='JavaScript')
plt.xlabel('Hour')
plt.ylabel('Interest')
plt.title('Hourly Interest for Python and JavaScript')
plt.legend()
plt.show()
此圖顯示了「Python」和「JavaScript」在指定時間範圍內的每小時興趣,使您可以比較它們的受歡迎程度並識別趨勢。
結論
在本文中,我們示範了如何使用 pytrends 函式庫中的 get_historical_interest() 函數從 Google Trends 擷取歷史每小時興趣資料。透過深入研究這些資料,您可以獲得有關搜尋詞受歡迎程度的寶貴洞察,並更好地理解消費者行為。本教學涵蓋了從設定 pytrends 請求到視覺化結果的整個收集和分析每小時興趣資料的過程。
NOTE : pytrends uses an unofficial API. Please use here for issues.
SAMPLE CODE : https://github.com/hobbyworker/google-trend-for-python