目录
一、案例背景
在全球旅游业蓬勃发展的当下,旅游市场的竞争愈发激烈。游客对于旅游目的地的选择日益多样化,受多种因素影响,如目的地的自然风光、文化底蕴、旅游设施以及社交媒体的推荐等。了解游客的偏好和市场趋势,对于旅游目的地的规划、营销以及旅游企业的决策至关重要。本案例将运用 Python 对热门旅游目的地的相关数据进行分析,挖掘背后的规律,为旅游行业相关方提供有价值的参考。
二、代码实现
import requests
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from wordcloud import WordCloud
import json
2.1 数据收集
从旅游点评网站、旅游局公开数据、社交媒体平台等多渠道收集数据。此处以模拟从旅游点评 API 和社交媒体 JSON 文件获取数据为例。
# 从旅游点评API获取热门旅游目的地的点评数据
travel_review_url = 'https://travel_review_api.com/destinations/reviews'
travel_review_headers = {
'Authorization': 'Bearer your_travel_review_api_token'
}
travel_review_response = requests.get(travel_review_url, headers=travel_review_headers)
travel_review_data = travel_review_response.json()
travel_review_df = pd.DataFrame(travel_review_data['reviews'])
# 从社交媒体获取旅游相关话题讨论数据
with open('social_media_travel.json', 'r', encoding='utf-8') as f:
social_travel_data = json.load(f)
social_travel_df = pd.DataFrame(social_travel_data)
2.2 数据探索性分析
# 查看旅游点评数据基本信息
print(travel_review_df.info())
# 查看社交媒体旅游讨论数据前几行
print(social_travel_df.head())
# 统计旅游点评数据中不同评分的数量
rating_count = travel_review_df['rating'].value_counts()
print(rating_count)
# 查看社交媒体旅游讨论数据中点赞数的分布情况
sns.histplot(social_travel_df['likes'], kde=True)
plt.title('Distribution of Likes in Social Media Travel Discussions')
plt.xlabel('Likes')
plt.ylabel('Count')
plt.show()
2.3 数据清洗
# 处理旅游点评数据的缺失值,填充评论为空的记录为'No comment'
travel_review_df['comment'] = travel_review_df['comment'].fillna('No comment')
# 处理社交媒体旅游讨论数据的文本,去除特殊字符和停用词
import re
from nltk.corpus import stopwords
import nltk
nltk.download('stopwords')
stop_words = set(stopwords.words('english'))
def clean_text(text):
text = re.sub(r'[^a-zA-Z]', ' ', text)
text = text.lower()
words = text.split()
filtered_words = [word for word in words if word not in stop_words]
return ' '.join(filtered_words)
social_travel_df['clean_text'] = social_travel_df['text'].apply(clean_text)
2.4 数据分析
2.4.1 旅游目的地评分分布分析
# 绘制旅游目的地评分的柱状图
plt.figure(figsize=(10, 6))
sns.countplot(x='rating', data=travel_review_df)
plt.title('Rating Distribution of Travel Destinations')
plt.xlabel('Rating')
plt.ylabel('Count')
plt.show()
2.4.2 社交媒体讨论热度趋势分析
# 将社交媒体讨论数据的发布日期列转换为日期时间类型
social_travel_df['post_date'] = pd.to_datetime(social_travel_df['post_date'])
social_travel_df['year_month'] = social_travel_df['post_date'].dt.to_period('M')
# 统计每月社交媒体讨