What we talk about when we talk about data science on Medium.com

Introduction

The data science community on the Medium.com has really exploded in the past few years, paralleling the data science boom. Browsing through the sheer deluge of data science articles published each day, I tend to cycle through intrigue, inadequacy, anxiety, boredom, clickbait fatigue, and some mixture of all of them. I think you likely have felt something similar.

Though, such a mountain of readily available data presents opportunities for analyses, so I decided to dive in to do some independent data science of my own. Turns out, this has been a great project for getting my feet wet with web scraping, data cleaning and natural language processing, none of which I have done before in any real sense. Plus, trying to sieve through the Medium data science hive mind feels like something that a website called “Intelligence Refinery” should do.


Getting the data

Web scraping - round 1

In the web scraping portion of the project, I collected, among other things, the URL, title, author name, publish date, tags, number of comments and number of “claps” of all articles with the tag “Data Science” published on Medium (earliest of which was published in 2009, but really picked up in volume in 2013).

Since I was completely new to web scraping before this, I looked around for existing and fairly recent scripts scraping Medium articles. I had found two that use Selenium (here and here), but because of the large size of data to be scraped, I wanted to use Scrapy over Selenium (see a comparison of the two here). Plus, Scrapy has a built-in selector system that means I don’t have to use BeautifulSoup to parse the HTML. I ended up using the Scrapy workflow by May Yeung (posted on Medium, of course) as a starting point and made the script below, after much trial and error.

Looking at the archive of all articles tagged with “Data Science”, I see that I can iterate over each year (2009-2019 November), each month (01-12) and each day (01-31) to see the story cards of all articles tagged with “Data Science”. Even though each story card contains the title, author name, publication date, number of comments and claps, I needed to get to the actual article page to get the tags. So, the script below follows the article URL on each story card to access the article page and scrape all the desired elements. This was the major departure from May Yeung’s workflow, which scraped only the story cards.

As there are often ~20,000 articles/year published in more recent years, I decided to divide up the scraping by year. As an example, here is the script used to get all the articles tagged with “Data Science” published in 2018:

## Import libraries
import scrapy
from scrapy.crawler import CrawlerProcess
from scrapy.utils.log import configure_logging
import logging
 
## Set working directory
import os
os.chdir('/Users/nancy/PycharmProjects/medium-ds-articles/data/raw/')
 
## Create container for scraped data
class Article(scrapy.Item):
    nameOfAuthor = scrapy.Field()
    linkOfAuthorProfile = scrapy.Field()
    NumOfComments = scrapy.Field()
    article = scrapy.Field()
    postingTime = scrapy.Field()
    NumOfClaps = scrapy.Field()
    articleURL = scrapy.Field()
    articleTags = scrapy.Field()
    readingTime = scrapy.Field()
 
## Set-up logging
logger = logging.getLogger('scrapylogger')
 
## Create crawler
class MediumSpider(scrapy.Spider):
    name = "medium_spider"
 
    configure_logging(install_root_handler=False)
    logging.basicConfig(
        filename='medium_full_2018_log.txt',
        format='%(levelname)s: %(message)s',
        level=logging.INFO
    )
 
    custom_settings = {
        'FEED_FORMAT': 'csv',
        'FEED_URI': 'medium_full_2018.csv',
        'AUTOTHROTTLE_ENABLED' : True,
        'AUTOTHROTTLE_START_DELAY' : 1,
        'AUTOTHROTTLE_MAX_DELAY' : 3
    }
 
    def start_requests(self):
        urls = []
 
        for month in range(1, 13):
            for day in range(1, 32):
                urls.append(f"https://medium.com/tag/data-science/archive/2018/{month:02}/{day:02}")
 
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)
 
 
 
    def parse(self, response):
        item = Article()
 
        for story in response.css('div.postArticle'):
            if story.css('div.postArticle-readMore a::attr(href)').extract_first() is not None:
                url = story.css('div.postArticle-readMore a::attr(href)').extract_first()
                yield scrapy.Request(url=url, callback=self.parse_full, meta={'item': item})
 
    def parse_full(self, response):
 
        item = response.meta['item']
        item['articleURL'] = response.request.url
        item['article'] = response.css('div.postArticle-content section div.section-content div h1::text, \
                                        div.postArticle-content section div.section-content div h1 a::text, \
                                        div.postArticle-content section div.section-content div h1 strong::text,\
                                        div.postArticle-content section div.section-content div h1 em::text, \
                                        div.postArticle-content section div.section-content div h3::text, \
                                        div.postArticle-content section div.section-content div h4::text, \
                                        div.postArticle-content section div.section-content div p strong::text, \
                                        div.postArticle-content section div.section-content div p strong em::text, \
                                        div.postArticle-content section div.section-content div p::text').extract_first()

        try:
            item['linkOfAuthorProfile'] = response.css('div.u-paddingBottom3 a').attrib['href']
        except KeyError:
            item['linkOfAuthorProfile'] = ' '
 
        try:
            item['readingTime'] = response.css('span.readingTime').attrib['title']
        except KeyError:
            item['readingTime'] = ' '
 
 
        item['nameOfAuthor'] = response.css('div.u-paddingBottom3 a::text').extract_first()
        item['postingTime'] = response.css('time::text').extract_first()
        item['articleTags'] = response.css('div.u-paddingBottom10 ul.tags--postTags li a::text').getall()
        item['NumOfComments'] = response.css(
            'div.buttonSet.u-flex0 button.button.button--chromeless.u-baseColor--buttonNormal.u-marginRight12::text').extract_first()
        item['NumOfClaps'] = response.xpath(
            '//div/main/article/footer/div[1]/div[3]/div/div[1]/div/span/button//text()').extract_first()
 
 
        yield item
 
 
process = CrawlerProcess({
    'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
})
 
process.crawl(MediumSpider)
process.start()

Web scraping - round 2

Just to see if for whatever reason I am missing some articles, I wrote a second crawler where I just scraped the article link from each story card. I do realize that there must be much simpler and more elegant ways of doing everything. However, this was my first attempt at web scraping, so I settled for the quickest way to get some data that I can analyze.

Here is the script for the simplified crawler:

Combine scraping results

Now that this is done, let’s peek at the two data sets for 2018:

1 2 3
NumOfClaps NaN NaN NaN
NumOfComments NaN NaN NaN
article The Woman Behind the Data Precisely How Buzz Monitoring Can Be A Compelling Factor For An Organisation Transforming Sales and Marketing through Data Analytics
articleTags Data,Datascience,Orlando Big Data,Data Science,Data Analysis Big Data,Data Analysis,Data Science
articleURL https://medium.com/@datawonderment/the-woman-behind-the-data-c908cf4999f6?source=tag_archive---------25--------------------- https://medium.com/@ankit.jain_86719/precisely-how-buzz-monitoring-can-be-a-compelling-factor-for-an-organisation-ea44e19dd756?source=tag_archive---------45--------------------- https://medium.com/@ankit.jain_86719/transforming-sales-and-marketing-through-data-analytics-967bf2c027c8?source=tag_archive---------49---------------------
linkOfAuthorProfile https://medium.com/@datawonderment https://medium.com/@ankit.jain_86719 https://medium.com/@ankit.jain_86719
nameOfAuthor Data Wonderment Canopus Infosystems Canopus Infosystems
postingTime Jan 1, 2018 Jan 1, 2018 Jan 3, 2018
readingTime 2 min read 2 min read 2 min read


article articleURL
AI and Machine Learning in Cyber Security https://towardsdatascience.com/ai-and-machine-learning-in-cyber-security-d6fbee480af0?source=tag_archive---------0---------------------
Redefining statistical significance: the statistical arguments https://medium.com/@richarddmorey/redefining-statistical-significance-the-statistical-arguments-ae9007bc1f91?source=tag_archive---------1---------------------
I do not understand t-SNE — Part 1 https://medium.com/@layog/i-dont-understand-t-sne-part-1-50f507acd4f9?source=tag_archive---------2---------------------
Statistical Analysis with Python: Pokémon https://medium.com/dataregressed/statistical-analysis-with-python-pok%C3%A9mon-1a72dd0451e1?source=tag_archive---------3---------------------
สอนให้เครื่องจักรเข้าใจภาษามนุษย์ภายใน code 3 บรรทัด (Python — Novice Level) https://medium.com/@dumpdatasci.th/%E0%B8%AA%E0%B8%AD%E0%B8%99%E0%B9%83%E0%B8%AB%E0%B9%89-%E0%B9%80%E0%B8%84%E0%B8%A3%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%87%E0%B8%88%E0%B8%B1%E0%B8%81%E0%B8%A3%E0%B9%80%E0%B8%82%E0%B9%89%E0%B8%B2%E0%B9%83%E0%B8%88%E0%B8%A0%E0%B8%B2%E0%B8%A9%E0%B8%B2%E0%B8%A1%E0%B8%99%E0%B8%B8%E0%B8%A9%E0%B8%A2%E0%B9%8C-code-python-3-%E0%B8%9A%E0%B8%A3%E0%B8%A3%E0%B8%97%E0%B8%B1%E0%B8%94-novice-level-12214ce838e4?source=tag_archive---------4---------------------
Data is Stupid https://medium.com/@noahyonack/data-is-stupid-52647a0b409f?source=tag_archive---------5---------------------


Theoretically, if my scraping is perfect in both cases, I would get the same number of articles/links from the two crawlers. However, a quick comparison of the two data sets, namely the “full-featured” article data that I got using the crawler in Part 1 and the more simplified “title-only” data gotten using the crawler above, showed that there are differences:

Full: (19698, 9)
Titles: (20127, 2)

Looking over the data sets, I see that there are duplicate links that only differ in the last part of the URLs (namely, ?source=tag_archive---------0---------------------). As the links are still valid after removing everything after ?, I did just that and deduplicated rows with idential article links.

(19653, 9)
(19678, 2)

Now the number of articles/links in the two datasets are much closer. Again, as this is a quick proof-of-concept and hobbey project, I’m not as concerned with getting all the data that I can possibly can. So, I will combine these two datasets to get all the unique article titles and metadata that I can, to get the final datasets that I will use for analysis. This is done in the same manner for articles tagged with “Data science” published in all years between 2009 and November 2019.

Just out of interest, let’s see how many data science articles are published each year since 2009:

Wow!


Data cleaning

Looking at the merged dataset for each year, I quickly see that there are issues with the scraped article titles. With Scrapy, I could use either CSS or XPath selectors to grab the desired elements form the HTML, which require that the formating of each story card and article page to be quite consistent. Surprisingly, for a blogging platform, the formatting of the elements was quite diverse, particularly of the article title. This led me to list all possible CSS selectors (XPath selectors didn’t do much better, so I omit those here) in an attempt to grab everything, but still I was getting some partial and blank titles.

As an example, you can see that I was getting only the first part (“Alastair Majury”) of several articles written by an author of the same name, even though there are more to the titles when I look at the article page directly.

NumOfClaps NumOfComments article articleLink articleTags linkOfAuthorProfile nameOfAuthor postingTime readingTime
31 3 claps NaN Aaron, https://medium.com/@dema300w/aaron-b6beb6de1dc4 Machine Learning,NLP,Fake News,Data Science,Artificial Intelligence https://medium.com/@dema300w Daniel DeMarco Jan 16, 2018
52 NaN NaN Alastair Majury https://medium.com/@majury1981/alastair-majury-on-can-the-cloud-improve-data-science-ef12bb56da83 Data Science,Cloud Computing,Alastair Majury,Data,Business Analysis https://medium.com/@majury1981 Alastair Majury Jan 15, 2018 3 min read
53 NaN NaN Alastair Majury https://medium.com/@majury1981/alastair-majury-on-common-myths-about-data-science-1b9e71b4a1ac Data Science,Data,Data Analysis,Alastair Majury,Business Analysis https://medium.com/@majury1981 Alastair Majury Jan 15, 2018 2 min read
54 NaN NaN Alastair Majury https://medium.com/@majury1981/alastair-majury-on-career-paths-for-analytics-majors-d52842ce19c1 Data Science,Data Analysis,Alastair Majury,Career Advice,Career Paths https://medium.com/@majury1981 Alastair Majury Jan 15, 2018 3 min read
56 NaN NaN Alastair Majury https://medium.com/@majury1981/alastair-majury-on-spotiq-should-business-analysts-be-worried-559ad732d35c Business Analyst,Financial Services,Dunblane,Data Science,Alastair Majury https://medium.com/@majury1981 Alastair Majury Jan 15, 2018 3 min read


I’m sure there are ways that I could have handled this better, but I noticed that the last part of each article URL contains pretty much the article title. So, I thought an easy way of getting clean-ish (emphasis on the -ish) article titles would be to parse the URLs.

So, I split each URL into parts by /, then further split the hyphen-separated portion and remove the alphanumeric artile ID at the very end. Finally, I put the cleaned strings into a new column, names.

Looking at the same truncated titles above, this approach seems to give me more info. Also, this seems to allow me to get some informative English words for article titles that are not in English.

article names articleLink
Aaron, aaron https://medium.com/@dema300w/aaron-b6beb6de1dc4
Alastair Majury alastair majury on can the cloud improve data science https://medium.com/@majury1981/alastair-majury-on-can-the-cloud-improve-data-science-ef12bb56da83
Alastair Majury alastair majury on common myths about data science https://medium.com/@majury1981/alastair-majury-on-common-myths-about-data-science-1b9e71b4a1ac
Alastair Majury alastair majury on career paths for analytics majors https://medium.com/@majury1981/alastair-majury-on-career-paths-for-analytics-majors-d52842ce19c1
Alastair Majury alastair majury on spotiq should business analysts be worried https://medium.com/@majury1981/alastair-majury-on-spotiq-should-business-analysts-be-worried-559ad732d35c
Alastair Majury alastair majury on how companies are using big data https://medium.com/@majury1981/alastair-majury-on-how-companies-are-using-big-data-4302737984bb
Alastair Majury alastair majury on data science the fastest growing industry https://medium.com/dataregressed/alastair-majury-on-data-science-the-fastest-growing-industry-cdcd7935f79c
Alastair Majury alastair majury on common interview questions for data scientist positions https://medium.com/dataregressed/alastair-majury-on-common-interview-questions-for-data-scientist-positions-10e7baef82f9
Hackweek XLIV hackweek xliv https://medium.com/liveramp-engineering/hackweek-xliv-c4306d1924cd
Alastair Majury alastair majury on the difference between a data scientist and a business analyst https://medium.com/@majury1981/alastair-majury-on-the-difference-between-a-data-scientist-and-a-business-analyst-8aa0b0ee4df2
Part 2 supervised machine learning dimensional reduction and principal component analysis https://hackernoon.com/supervised-machine-learning-dimensional-reduction-and-principal-component-analysis-614dec1f6b4c
IPython データサイエンスクックブックを読んだ ipython data science book https://medium.com/moonshot/ipython-data-science-book-7c9257293fdf
輿論分析量測電視劇觀看喜好的風向 %E8%BC%BF%E8%AB%96%E5%88%86%E6%9E%90%E9%87%8F%E6%B8%AC%E9%9B%BB%E8%A6%96%E5%8A%87%E8%A7%80%E7%9C%8B%E5%96%9C%E5%A5%BD%E7%9A%84%E9%A2%A8%E5%90%91 https://medium.com/kkstream/%E8%BC%BF%E8%AB%96%E5%88%86%E6%9E%90%E9%87%8F%E6%B8%AC%E9%9B%BB%E8%A6%96%E5%8A%87%E8%A7%80%E7%9C%8B%E5%96%9C%E5%A5%BD%E7%9A%84%E9%A2%A8%E5%90%91-c9c4993f959d
Hello Hadoop! hello hadoop https://medium.com/@arnkamath2004/hello-hadoop-f069dd4f32d9
Dave, dave https://medium.com/@thomas_72192/dave-767203306675


It’s not perfect, but let’s give this a try for now.


Identify common bigrams in article titles

As my first analysis, I really want to see if there are some patterns/trends in the article titles. Particularly, if popular topics have evolved over the year and just how clickbait-y the article titles have become. Here, I will use the workflow presented in the excellent reference “Text Mining with R” for extracting word pairs (bigrams) from a corpus and examining their relationships.

Get title bigram counts

First, I will use the Python natural language processing packages NLTK and spaCy to tokenize each (parsed) article title, filter out non-English words, singularize nouns, generate bigrams and finally create a tally of the frequency of each bigram. Unlike many other examples I have seen, I opted to not remove stop words, as otherwise I would lose bigrams like ‘how’, ‘to’ and ‘need’, ‘to’ that are so prevalent in Medium articles and hallmarks for clickbait.

word1 word2 n
data science 2374
machine learning 1287
how to 812
data scientist 475
a data 454
part 1 363
for data 345
deep learning 322
in python 310
big data 306


Unsurprisingly, “data science”, “machine learning” and “how to” are the most frequently appearing bigrams in article titles. Looks like we are on the right track.


Visualize bigram relationships

Finally, I will use the R packages igraph and ggraph to visualize the relationship between the top 60 (otherwise the figure is too crowded) most frequently appearing bigrams in titles of Medium articles tagged with “Data science” published in 2018.

Each word appears as a node and the directionality of the arrow connecting them to each other indicates the order in which they appears in a bigram. Finally, the darkness of the arrow connecting each pair of words is proportional to the frequency of appearance for that bigram. For example, we see much darker arrows connecting ‘data’, ‘science’ or ‘machine’, ‘learning’.

Yep, we are seeing the “need to”, “how to”, “the best” that just sends a stab of FOMO through your heart.

Anyways! Please head over to this nifty Shiny dashboard to explore the most frequently appearing bigrams in the titles of Medium data science articles published between 2009 and 2019 (as of November 21st).


Session info

R version 3.6.0 (2019-04-26)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Mojave 10.14.6

Matrix products: default
BLAS:   /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRlapack.dylib

locale:
[1] en_CA.UTF-8/en_CA.UTF-8/en_CA.UTF-8/C/en_CA.UTF-8/en_CA.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] ggraph_2.0.0     igraph_1.2.4.1   ggplot2_3.2.1    magrittr_1.5    
 [5] dplyr_0.8.3      plyr_1.8.4       kableExtra_1.1.0 reticulate_1.13 
 [9] rmdformats_0.3.5 knitr_1.26      

loaded via a namespace (and not attached):
 [1] ggrepel_0.8.1      Rcpp_1.0.3         lattice_0.20-38    tidyr_1.0.0       
 [5] assertthat_0.2.1   zeallot_0.1.0      digest_0.6.23      ggforce_0.3.1     
 [9] mime_0.7           R6_2.4.1           backports_1.1.5    evaluate_0.14     
[13] httr_1.4.1         highr_0.8          pillar_1.4.2       rlang_0.4.2.9000  
[17] lazyeval_0.2.2     rstudioapi_0.10    miniUI_0.1.1.1     Matrix_1.2-17     
[21] rmarkdown_1.18     labeling_0.3       webshot_0.5.1      readr_1.3.1       
[25] stringr_1.4.0      questionr_0.7.0    polyclip_1.10-0    munsell_0.5.0     
[29] shiny_1.3.2        compiler_3.6.0     httpuv_1.5.2       xfun_0.11         
[33] pkgconfig_2.0.3    htmltools_0.4.0    tidyselect_0.2.5   gridExtra_2.3     
[37] tibble_2.1.3       bookdown_0.15      graphlayouts_0.5.0 codetools_0.2-16  
[41] viridisLite_0.3.0  crayon_1.3.4       withr_2.1.2        later_1.0.0       
[45] MASS_7.3-51.4      grid_3.6.0         jsonlite_1.6       xtable_1.8-4      
[49] gtable_0.3.0       lifecycle_0.1.0    formatR_1.7        scales_1.0.0      
[53] stringi_1.4.3      farver_1.1.0       viridis_0.5.1      promises_1.1.0    
[57] xml2_1.2.2         vctrs_0.2.0        tools_3.6.0        glue_1.3.1        
[61] tweenr_1.0.1       purrr_0.3.3        hms_0.5.2          yaml_2.2.0        
[65] colorspace_1.4-1   tidygraph_1.1.2    rvest_0.3.5       

Nancy Chelaru

2019-11-28