租房有深坑?手把手教你如何用R速读评论+科学选房

大数据 数据分析
要想租到称心如意的房子,不仅要眼明手快,还得看清各类“前辈”的评价避开大坑。一位程序员在出行选酒店的时候就借用了程序工具:先用python爬下了海外点评网站TripAdvisor的数千评论,并且用R进行了文本分析和情感分析,科学选房,高效便捷,极具参考价值。

[[242297]]

大数据文摘出品

编译:Hope、臻臻、CoolBoy

最近,租房这事儿成了北漂族的一大bug,要想租到称心如意的房子,不仅要眼明手快,还得看清各类“前辈”的评价避开大坑。一位程序员在出行选酒店的时候就借用了程序工具:先用python爬下了海外点评网站TripAdvisor的数千评论,并且用R进行了文本分析和情感分析,科学选房,高效便捷,极具参考价值。

以下,这份超详实的教程拿好不谢。

TripAdvisor提供的信息对于旅行者的出行决策非常重要。但是,要去了解TripAdvisor的泡沫评分和数千个评论文本之间的细微差别是极具挑战性的。

为了更加全面地了解酒店旅客的评论是否会对之后酒店的服务产生影响,我爬取了TripAdvisor中一个名为Hilton Hawaiian Village酒店的所有英文评论。这里我不会对爬虫的细节进行展开。

Python源码:

https://github.com/susanli2016/NLP-with-Python/blob/master/Web%20scraping%20Hilton%20Hawaiian%20Village%20TripAdvisor%20Reviews.py

加载扩展包

  • library(dplyr)
  • library(readr)
  • library(lubridate)
  • library(ggplot2)
  • library(tidytext)
  • library(tidyverse)
  • library(stringr)
  • library(tidyr)
  • library(scales)
  • library(broom)
  • library(purrr)
  • library(widyr)
  • library(igraph)
  • library(ggraph)
  • library(SnowballC)
  • library(wordcloud)
  • library(reshape2)
  • theme_set(theme_minimal())

数据集

  1. df <- read_csv("Hilton_Hawaiian_Village_Waikiki_Beach_Resort-Honolulu_Oahu_Hawaii__en.csv") 
  2. df <- df[complete.cases(df), ] 
  3. df$review_date <- as.Date(df$review_date, format = "%d-%B-%y"
  4.  
  5. dim(df); min(df$review_date); max(df$review_date) 

Figure 2

我们在TripAdvisor上一共获得了13,701条关于Hilton Hawaiian Village酒店的英文评论,这些评论的时间范围是从2002–03–21 到2018–08–02。

  1. df %>
  2.   count(Week = round_date(review_date, "week")) %>
  3.   ggplot(aes(Week, n)) + 
  4.   geom_line() +  
  5.   ggtitle('The Number of Reviews Per Week') 

Figure 2

在2014年末,周评论数量达到最高峰。那一个星期里酒店被评论了70次。

对评论文本进行文本挖掘

  1. df <- tibble::rowid_to_column(df, "ID") 
  2. df <- df %>
  3.   mutate(review_date = as.POSIXct(review_date, origin = "1970-01-01"),month = round_date(review_date, "month")) 
  4.  
  5. review_words <- df %>
  6.   distinct(review_body, .keep_all = TRUE) %>
  7.   unnest_tokens(word, review_body, drop = FALSE) %>
  8.   distinct(ID, word, .keep_all = TRUE) %>
  9.   anti_join(stop_words, by = "word") %>
  10.   filter(str_detect(word, "[^\\d]")) %>
  11.   group_by(word) %>
  12.   mutate(word_total = n()) %>
  13.   ungroup() 
  14.  
  15. word_counts <- review_words %>
  16.   count(word, sort = TRUE
  17.  
  18. word_counts %>
  19.   head(25) %>
  20.   mutate(word = reorder(word, n)) %>
  21.   ggplot(aes(word, n)) + 
  22.   geom_col(fill = "lightblue") + 
  23.   scale_y_continuous(labels = comma_format()) + 
  24.   coord_flip() + 
  25.   labs(title = "Most common words in review text 2002 to date"
  26.        subtitle = "Among 13,701 reviews; stop words removed"
  27.        y = "# of uses"

Figure 3

我们还可以更进一步的把“stay”和“stayed”,“pool”和“pools”这些意思相近的词合并起来。这个步骤被称为词干提取,也就是将变形(或是衍生)词语缩减为词干,基词或根词的过程。

  1. word_counts %>
  2.   head(25) %>
  3.   mutate(word = wordStem(word)) %>%  
  4.   mutate(word = reorder(word, n)) %>
  5.   ggplot(aes(word, n)) + 
  6.   geom_col(fill = "lightblue") + 
  7.   scale_y_continuous(labels = comma_format()) + 
  8.   coord_flip() + 
  9.   labs(title = "Most common words in review text 2002 to date"
  10.        subtitle = "Among 13,701 reviews; stop words removed and stemmed"
  11.        y = "# of uses"

Figure 4

二元词组

通常我们希望了解评论中单词的相互关系。哪些词组在评论文本中比较常用呢?如果给出一列单词,那么后面会随之出现什么单词呢?哪些词之间的关联性最强?许多有意思的文本挖掘都是基于这些关系的。在研究两个连续单词的时候,我们称这些单词对为“二元词组”。

所以,在Hilton Hawaiian Village的评论中,哪些是最常见的二元词组呢?

  1. review_bigrams <- df %>
  2.   unnest_tokens(bigram, review_body, token = "ngrams"n = 2
  3.  
  4. bigrams_separated <- review_bigrams %>
  5.   separate(bigram, c("word1", "word2"), sep = " "
  6.  
  7. bigrams_filtered <- bigrams_separated %>
  8.   filter(!word1 %in% stop_words$word) %>
  9.   filter(!word2 %in% stop_words$word) 
  10.  
  11. bigram_counts <- bigrams_filtered %>%  
  12.   count(word1, word2, sort = TRUE
  13.  
  14. bigrams_united <- bigrams_filtered %>
  15.   unite(bigram, word1, word2, sep = " "
  16.  
  17. bigrams_united %>
  18.   count(bigram, sort = TRUE

Figure 5

最常见的二元词组是“rainbow tower”(彩虹塔),其次是“hawaiian village”(夏威夷村)。

我们可以利用网络可视化来展示这些二元词组:

  1. review_subject <- df %>%  
  2.   unnest_tokens(word, review_body) %>%  
  3.   anti_join(stop_words) 
  4.  
  5. my_stopwords <- data_frame(word = c(as.character(1:10))) 
  6. review_subject <- review_subject %>%  
  7.   anti_join(my_stopwords) 
  8.  
  9. title_word_pairs <- review_subject %>%  
  10.   pairwise_count(word, ID, sort = TRUEupper = FALSE
  11.  
  12. set.seed(1234) 
  13. title_word_pairs %>
  14.   filter(n >= 1000) %>
  15.   graph_from_data_frame() %>
  16.   ggraph(layout = "fr") + 
  17.   geom_edge_link(aes(edge_alpha = nedge_width = n), edge_colour = "cyan4") + 
  18.   geom_node_point(size = 5) + 
  19.   geom_node_text(aes(label = name), repel = TRUE,  
  20.                  point.padding = unit(0.2, "lines")) + 
  21.   ggtitle('Word network in TripAdvisor reviews') 
  22.   theme_void() 

Figure 6

上图展示了TripAdvisor评论中较为常见的二元词组。这些词至少出现了1000次,而且其中不包含停用词。

在网络图中我们发现出现频率最高的几个词存在很强的相关性(“hawaiian”, “village”, “ocean” 和“view”),不过我们没有发现明显的聚集现象。

三元词组

二元词组有时候还不足以说明情况,让我们来看看TripAdvisor中关于Hilton Hawaiian Village酒店最常见的三元词组有哪些。

  1. review_trigrams <- df %>
  2.   unnest_tokens(trigram, review_body, token = "ngrams"n = 3
  3.  
  4. trigrams_separated <- review_trigrams %>
  5.   separate(trigram, c("word1", "word2", "word3"), sep = " "
  6.  
  7. trigrams_filtered <- trigrams_separated %>
  8.   filter(!word1 %in% stop_words$word) %>
  9.   filter(!word2 %in% stop_words$word) %>
  10.   filter(!word3 %in% stop_words$word) 
  11.  
  12. trigram_counts <- trigrams_filtered %>%  
  13.   count(word1, word2, word3, sort = TRUE
  14.  
  15. trigrams_united <- trigrams_filtered %>
  16.   unite(trigram, word1, word2, word3, sep = " "
  17.  
  18. trigrams_united %>
  19.   count(trigram, sort = TRUE

Figure 7

最常见的三元词组是“hilton hawaiian village”,其次是“diamond head tower”,等等。

评论中关键单词的趋势

随着时间的推移,哪些单词或话题变得更加常见,或者更加罕见了呢?从这些信息我们可以探知酒店做出的调整,比如在服务上,翻新上,解决问题上。我们还可以预测哪些主题会更多地被提及。

我们想要解决类似这样的问题:随着时间的推移,在TripAdvisor的评论区中哪些词出现的频率越来越高了?

  1. reviews_per_month <- df %>
  2.   group_by(month) %>
  3.   summarize(month_total = n()) 
  4.  
  5. word_month_counts <- review_words %>
  6.   filter(word_total >= 1000) %>
  7.   count(word, month) %>
  8.   complete(word, month, fill = list(n = 0)) %>
  9.   inner_join(reviews_per_month, by = "month") %>
  10.   mutate(percent = n / month_total) %>
  11.   mutate(yearyear = year(month) + yday(month) / 365) 
  12.  
  13. mod <- ~ glm(cbind(n, month_total - n) ~ year, ., family = "binomial"
  14.  
  15. slopes <- word_month_counts %>
  16.   nest(-word) %>
  17.   mutate(model = map(data, mod)) %>
  18.   unnest(map(model, tidy)) %>
  19.   filter(term == "year") %>
  20.   arrange(desc(estimate)) 
  21.  
  22. slopes %>
  23.   head(9) %>
  24.   inner_join(word_month_counts, by = "word") %>
  25.   mutate(word = reorder(word, -estimate)) %>
  26.   ggplot(aes(month, n / month_total, color = word)) + 
  27.   geom_line(show.legend = FALSE) + 
  28.   scale_y_continuous(labels = percent_format()) + 
  29.   facet_wrap(~ word, scales = "free_y") + 
  30.   expand_limits(y = 0) + 
  31.   labs(x = "Year"
  32.        y = "Percentage of reviews containing this word"
  33.        title = "9 fastest growing words in TripAdvisor reviews"
  34.        subtitle = "Judged by growth rate over 15 years"

Figure 8

在2010年以前我们可以看到大家讨论的焦点是“friday fireworks”(周五的烟花)和“lagoon”(环礁湖)。而在2005年以前“resort fee”(度假费)和“busy”(繁忙)这些词的词频增长最快。

评论区中哪些词的词频在下降呢?

  1. slopes %>
  2.   tail(9) %>
  3.   inner_join(word_month_counts, by = "word") %>
  4.   mutate(word = reorder(word, estimate)) %>
  5.   ggplot(aes(month, n / month_total, color = word)) + 
  6.   geom_line(show.legend = FALSE) + 
  7.   scale_y_continuous(labels = percent_format()) + 
  8.   facet_wrap(~ word, scales = "free_y") + 
  9.   expand_limits(y = 0) + 
  10.   labs(x = "Year"
  11.        y = "Percentage of reviews containing this term"
  12.        title = "9 fastest shrinking words in TripAdvisor reviews"
  13.        subtitle = "Judged by growth rate over 4 years"

Figure 9

这张图展示了自2010年以来逐渐变少的主题。这些词包括“hhv” (我认为这是 hilton hawaiian village的简称), “breakfast”(早餐), “upgraded”(升级), “prices”(价格) and “free”(免费)。

让我们对一些单词进行比较。

  1. word_month_counts %>
  2.   filter(word %in% c("service", "food")) %>
  3.   ggplot(aes(month, n / month_total, color = word)) + 
  4.   geom_line(size = 1alpha = .8) + 
  5.   scale_y_continuous(labels = percent_format()) + 
  6.   expand_limits(y = 0) + 
  7.   labs(x = "Year"
  8.        y = "Percentage of reviews containing this term"title = "service vs food in terms of reviewers interest"

Figure 10

在2010年之前,服务(service)和食物(food)都是热点主题。关于服务和食物的讨论在2003年到达顶峰,自2005年之后就一直在下降,只是偶尔会反弹。

情感分析

情感分析被广泛应用于对评论、调查、网络和社交媒体文本的分析,以反映客户的感受,涉及范围包括市场营销、客户服务和临床医学等。

在本案例中,我们的目标是对评论者(也就是酒店旅客)在住店之后对酒店的态度进行分析。这个态度可能是一个判断或是评价。

下面来看评论中出现得最频繁的积极词汇和消极词汇。

  1. reviews <- df %>%  
  2.   filter(!is.na(review_body)) %>%  
  3.   select(ID, review_body) %>%  
  4.   group_by(row_number()) %>%  
  5.   ungroup() 
  6. tidy_reviews <- reviews %>
  7.   unnest_tokens(word, review_body) 
  8. tidy_reviews <- tidy_reviews %>
  9.   anti_join(stop_words) 
  10.  
  11. bing_word_counts <- tidy_reviews %>
  12.   inner_join(get_sentiments("bing")) %>
  13.   count(word, sentiment, sort = TRUE) %>
  14.   ungroup() 
  15.  
  16. bing_word_counts %>
  17.   group_by(sentiment) %>
  18.   top_n(10) %>
  19.   ungroup() %>
  20.   mutate(word = reorder(word, n)) %>
  21.   ggplot(aes(word, n, fill = sentiment)) + 
  22.   geom_col(show.legend = FALSE) + 
  23.   facet_wrap(~sentiment, scales = "free") + 
  24.   labs(y = "Contribution to sentiment"x = NULL) + 
  25.   coord_flip() +  
  26.   ggtitle('Words that contribute to positive and negative sentiment in the reviews') 

Figure 11

让我们换一个情感文本库,看看结果是否一样。

  1. contributions <- tidy_reviews %>
  2.   inner_join(get_sentiments("afinn"), by = "word") %>
  3.   group_by(word) %>
  4.   summarize(occurences = n(), 
  5.             contribution = sum(score)) 
  6. contributions %>
  7.   top_n(25, abs(contribution)) %>
  8.   mutate(word = reorder(word, contribution)) %>
  9.   ggplot(aes(word, contribution, fill = contribution > 0)) + 
  10.   ggtitle('Words with the greatest contributions to positive/negative  
  11.           sentiment in reviews') + 
  12.   geom_col(show.legend = FALSE) + 
  13.   coord_flip() 

Figure 12

有意思的是,“diamond”(出自“diamond head-钻石头”)被归类为积极情绪。

这里其实有一个潜在问题,比如“clean”(干净)是什么词性取决于语境。如果前面有个“not”(不),这就是一个消极情感了。事实上一元词在否定词(如not)存在的时候经常碰到这种问题,这就引出了我们下一个话题:

在情感分析中使用二元词组来辨明语境

我们想知道哪些词经常前面跟着“not”(不)

  1. bigrams_separated %>
  2.   filter(word1 == "not") %>
  3.   count(word1, word2, sort = TRUE

Figure 13

“a”前面跟着“not”的情况出现了850次,而“the”前面跟着“not”出现了698次。不过,这种结果不是特别有实际意义。

  1. AFINN <- get_sentiments("afinn") 
  2. not_words <- bigrams_separated %>
  3.   filter(word1 == "not") %>
  4.   inner_join(AFINN, by = c(word2 = "word")) %>
  5.   count(word2, score, sort = TRUE) %>
  6.   ungroup() 
  7.  
  8. not_words 

Figure 14

上面的分析告诉我们,在“not”后面最常见的情感词汇是“worth”,其次是“recommend”,这些词都被认为是积极词汇,而且积极程度得分为2。

所以在我们的数据中,哪些单词最容易被误解为相反的情感?

  1. not_words %>
  2.   mutate(contribution = n * score) %>
  3.   arrange(desc(abs(contribution))) %>
  4.   head(20) %>
  5.   mutate(word2 = reorder(word2, contribution)) %>
  6.   ggplot(aes(word2, n * score, fill = n * score > 0)) + 
  7.   geom_col(show.legend = FALSE) + 
  8.   xlab("Words preceded by \"not\"") + 
  9.   ylab("Sentiment score * number of occurrences") + 
  10.   ggtitle('The 20 words preceded by "not" that had the greatest contribution to  
  11.           sentiment scores, positive or negative direction') + 
  12.   coord_flip() 

Figure 15

二元词组“not worth”, “not great”, “not good”, “not recommend”和“not like”是导致错误判断的最大根源,使得评论看起来比原来积极的多。

除了“not”以外,还有其他的否定词会对后面的内容进行情绪的扭转,比如“no”, “never” 和“without”。让我们来看一下具体情况。

  1. negation_words <- c("not", "no", "never", "without") 
  2.  
  3. negated_words <- bigrams_separated %>
  4.   filter(word1 %in% negation_words) %>
  5.   inner_join(AFINN, by = c(word2 = "word")) %>
  6.   count(word1, word2, score, sort = TRUE) %>
  7.   ungroup() 
  8.  
  9. negated_words %>
  10.   mutate(contribution = n * score, 
  11.          word2 = reorder(paste(word2, word1, sep = "__"), contribution)) %>
  12.   group_by(word1) %>
  13.   top_n(12, abs(contribution)) %>
  14.   ggplot(aes(word2, contribution, fill = n * score > 0)) + 
  15.   geom_col(show.legend = FALSE) + 
  16.   facet_wrap(~ word1, scales = "free") + 
  17.   scale_x_discrete(labels = function(x) gsub("__.+$", "", x)) + 
  18.   xlab("Words preceded by negation term") + 
  19.   ylab("Sentiment score * # of occurrences") + 
  20.   ggtitle('The most common positive or negative words to follow negations  
  21.           such as "no", "not", "never" and "without"') + 
  22.   coord_flip() 

Figure 16

看来导致错判为积极词汇的最大根源来自于“not worth/great/good/recommend”,而另一方面错判为消极词汇的最大根源是“not bad” 和“no problem”。

最后,让我们来观察一下最积极和最消极的评论。

  1. sentiment_messages <- tidy_reviews %>
  2.   inner_join(get_sentiments("afinn"), by = "word") %>
  3.   group_by(ID) %>
  4.   summarize(sentiment = mean(score), 
  5.             words = n()) %>
  6.   ungroup() %>
  7.   filter(words >= 5) 
  8.  
  9. sentiment_messages %>
  10.   arrange(desc(sentiment)) 

Figure 17

最积极的评论来自于ID为2363的记录:“哇哇哇,这地方太好了!从房间我们可以看到很漂亮的景色,我们住得很开心。Hilton酒店就是很棒!无论是小孩还是大人,这家酒店有着所有你想要的东西。”

  1. df[ which(df$ID==2363), ]$review_body[1] 

Figure 18

  1. sentiment_messages %>
  2.   arrange(sentiment) 

Figure 19

最消极的评论来自于ID为3748的记录:“(我)住了5晚(16年5月12日-5月17日)。第一晚,我们发现地砖坏了,小孩子在玩手指。第二晚,我们看到小蟑螂在儿童食物上爬。前台给我们换了房间,但他们让我们一小时之内搬好房间,否则就不能换房。。。已经晚上11点,我们都很累了,孩子们也睡了。我们拒绝了这个建议。退房的时候,前台小姐跟我讲,蟑螂在他们的旅馆里很常见。她还反问我在加州见不到蟑螂吗?我没想到能在Hilton遇到这样的事情。”

  1. df[ which(df$ID==3748), ]$review_body[1] 

Figure 20

Github源码:

https://github.com/susanli2016/Data-Analysis-with-R/blob/master/Text%20Mining%20Hilton%20Hawaiian%20Village%20TripAdvisor%20Reviews.Rmd

相关报道:

https://towardsdatascience.com/scraping-tripadvisor-text-mining-and-sentiment-analysis-for-hotel-reviews-cc4e20aef333

【本文是51CTO专栏机构大数据文摘的原创文章,微信公众号“大数据文摘( id: BigDataDigest)”】

     大数据文摘二维码

戳这里,看该作者更多好文

责任编辑:赵宁宁 来源: 51CTO专栏
相关推荐

2009-03-18 11:36:21

代理服务器下载MyEclipse7.

2014-11-17 11:13:17

易维

2022-12-07 08:42:35

2022-07-27 08:16:22

搜索引擎Lucene

2021-07-14 09:00:00

JavaFX开发应用

2023-10-28 08:51:35

Java多线程服务

2011-05-03 15:59:00

黑盒打印机

2011-01-10 14:41:26

2022-06-06 08:50:40

CIOIT转型

2021-01-19 09:06:21

MysqlDjango数据库

2014-08-08 13:22:54

测试手机站点移动设备

2022-01-08 20:04:20

拦截系统调用

2023-04-26 12:46:43

DockerSpringKubernetes

2022-03-14 14:47:21

HarmonyOS操作系统鸿蒙

2010-07-06 09:38:51

搭建私有云

2010-07-06 09:43:57

搭建私有云

2021-11-09 06:55:03

水印图像开发

2015-07-15 13:18:27

附近的人开发

2020-08-12 09:07:53

Python开发爬虫

2020-12-21 09:47:16

UbuntuMinicondalinux
点赞
收藏

51CTO技术栈公众号