概述
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