<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by TU on Medium]]></title>
        <description><![CDATA[Stories by TU on Medium]]></description>
        <link>https://medium.com/@tinau-87758?source=rss-a66fcb410541------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yUgJXFAaNvZny6bvlUvKTQ.jpeg</url>
            <title>Stories by TU on Medium</title>
            <link>https://medium.com/@tinau-87758?source=rss-a66fcb410541------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 21:02:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tinau-87758/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to cluster similar sentences using TF-IDF and Graph partitioning in Python]]></title>
            <link>https://medium.com/data-science/how-to-cluster-similar-sentences-using-tf-idf-and-graph-partitioning-in-python-5fb70627a4e0?source=rss-a66fcb410541------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fb70627a4e0</guid>
            <category><![CDATA[network]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[TU]]></dc:creator>
            <pubDate>Mon, 01 Feb 2021 13:31:37 GMT</pubDate>
            <atom:updated>2021-02-01T13:31:37.278Z</atom:updated>
            <content:encoded><![CDATA[<h4>What data science articles gain more attraction from the readers (Part 2)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*octrwZI91krSmowX" /><figcaption>Photo by <a href="https://unsplash.com/@hansonluu?utm_source=medium&amp;utm_medium=referral">Hanson Lu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this series of articles we are analysing historical archives of data science publications to understand what topics are more popular with the readers. Previously we covered <a href="https://medium.com/analytics-vidhya/what-data-science-articles-attract-more-attention-part-1-efe8faf209d0">how to get the data</a> that will be used for further analysis.</p><p>We will cover how to clean text data we collected earlier , group similar topics using network graphs and establish patterns within these clusters in this article.</p><h4>Data summary</h4><p>Let’s remind ourselves how the data looks like. It is combination of articles obtained from three data sources [field: ‘Source’] — <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> [‘avd’], <a href="https://towardsdatascience.com/">TDS</a> [‘tds’] and <a href="https://medium.com/towards-artificial-intelligence">Towards AI</a> [‘tai’].</p><p>We collected titles, subtitles, claps and responses from individual articles in archives of the publications.</p><pre>import pandas as pd</pre><pre># Reading the data obtained using code <a href="https://medium.com/analytics-vidhya/what-data-science-articles-attract-more-attention-part-1-efe8faf209d0">here</a>.<br>avd = pd.read_csv(&#39;analytics_vidhya_data.csv&#39;)<br>tds = pd.read_csv(&#39;medium_articles.csv&#39;)<br>tai = pd.read_csv(&#39;towards_ai_data.csv&#39;)</pre><pre>avd[&#39;source&#39;] = &#39;avd&#39;<br>tds[&#39;source&#39;] = &#39;tds&#39;<br>tai[&#39;source&#39;] = &#39;tai&#39;</pre><pre># Create single data set, join title and subtitle<br>single_matrix = pd.concat([avd, tds, tai])<br>single_matrix[&#39;title_subtitle&#39;] = [&#39; &#39;.join([str(i),str(j)]) for i, j in zip(single_matrix[&#39;Title&#39;].fillna(&#39;&#39;), single_matrix[&#39;Subtitle&#39;].fillna(&#39;&#39;))]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WxMbXCerqajYJNIfqcnQXA.png" /><figcaption>Articles data set</figcaption></figure><p>We added an additional column in the data set called ‘title_subtitle’ which is the join of columns <em>‘Title’ </em>and <em>‘Subtitle’</em>, we will mainly use this column in order to have a better view of the topic the article belongs to. Quite interestingly <em>39% </em>of articles don’t have subtitles and a very small proportion <em>(0.13%)</em> don’t have titles.</p><p>Let’s quickly look at the claps and responses distributions for every data source. We start with box plots, we use <em>seaborn</em> library in Python to create our plots.</p><pre># We will use seaborn to create all plots<br>import seaborn as sns<br>import matplotlib.pyplot as plt</pre><pre>fig, axes = plt.subplots(1, 2, figsize=(8, 5))<br># Claps<br>sns.boxplot(ax=axes[0], x=&quot;source&quot;, y=&quot;Claps&quot;, data=single_matrix)</pre><pre># Responses<br>sns.boxplot(ax=axes[1], x=&quot;source&quot;, y=&quot;Responses&quot;, data=single_matrix)</pre><p>We can see that Towards Data Science has not only more activity, but also quite a few outliers with individual articles gaining a lot of attraction from readers. Of course, the activity for each source depends on the size of publication, for larger publications we observe more writers and readers.</p><p>When it comes to responses, we observe far less activity in comparison to claps across all sources, although such behaviour is not very unexpected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vaUZIXWDd9NB9jfAdpRYNg.png" /><figcaption>Box plots for claps and responses split by source</figcaption></figure><p>Next, we remove outliers and visualise distributions of the fields to have a clearer picture.</p><pre># Code to create distribution subplots<br>fig, axes = plt.subplots(2, 1, figsize=(8, 8))</pre><pre># Claps<br>sns.distplot(avd[&#39;Claps&#39;][avd[&#39;Claps&#39;]&lt;10000], hist=True, rug=False, ax=axes[0])<br>sns.distplot(tds[&#39;Claps&#39;][tds[&#39;Claps&#39;]&lt;10000], hist=True, rug=False, ax=axes[0])<br>sns.distplot(tai[&#39;Claps&#39;][tai[&#39;Claps&#39;]&lt;10000], hist=True, rug=False, ax=axes[0])</pre><pre># Responses<br>sns.distplot(avd[&#39;Responses&#39;], hist=True, rug=False, ax=axes[1])<br>sns.distplot(tds[&#39;Responses&#39;], hist=True, rug=False, ax=axes[1])<br>sns.distplot(tai[&#39;Responses&#39;], hist=True, rug=False, ax=axes[1])</pre><p>We can see that both distributions are skewed to the left, meaning that the most articles get very little claps and even less responses. Yet again this is not surprising, since the success of articles depends on many factors, such as good quality writing, relevant topics and many more. Striking a good balance is not a simple task!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0JdswnREc24Yz-9938C8xQ.png" /><figcaption>Claps and responses distributions split by sources</figcaption></figure><h4>How to clean text data?</h4><p>Cleaning data is an important step (if not the most important part) when working with text. There are standard practices in place that one follows when dealing with such tasks. We will undertake following steps to process titles and subtitles:</p><ul><li>remove punctuation marks and other symbols</li><li>remove stop words and digits</li><li>lemmatise words</li></ul><p>We will use a mixture of regular expressions and<em> nltk </em>library to<strong><em> remove punctuation marks, symbols, stop words and digits</em></strong><em>.</em></p><pre>import re<br>single_matrix[&#39;title_subtitle&#39;] = [re.findall(r&#39;\w+&#39;, i.lower()) for i in single_matrix[&#39;title_subtitle&#39;].fillna(&#39;NONE&#39;)]</pre><p>The code above matches one or more word characters, in fact <em>r’\w+’</em> is the same as <em>r’[a-zA-Z0–9_]+’. </em>Also, when applying <em>re.findall()</em> and <em>i.lower()</em> commands, they conveniently split sentences into words and transform them into lower case. This will come very useful in next steps. So, the sentence <em>‘Reporting In Qlikview | Ad Hoc Reporting’</em> becomes <em>[reporting, in, qlikview, ad, hoc, reporting].</em></p><p>Next, we will use <em>nltk</em> library to upload a dictionary of stop words so we can remove them from the sentences. Additionally we append words ‘use’ and ‘part ‘ to the list, since they are overused in the data set. To remove the stop words we use for loop to iterate over each sentence, when doing so we also ensure to remove the digits from the sentences.</p><pre># The code to upload list of stop words and remove them from sentences</pre><pre>import nltk<br>nltk.download(&#39;stopwords&#39;) <br>from nltk.corpus import stopwords</pre><pre>stopwords_eng = stopwords.words(&#39;english&#39;)  <br>stopwords_eng += [&#39;use&#39;, &#39;using&#39;, &#39;used&#39;, &#39;part&#39;]</pre><pre>new_titles_sub = []<br>for title_sub in single_matrix[&#39;new_title_subtitle&#39;]:<br>    new_title_sub = []<br>    for w_title in title_sub:<br>        if w_title not in stopwords_eng and not w_title.isdigit():<br>            new_title_sub.append(w_title)<br>    <br>    new_titles_sub.append(new_title_sub) <br>    <br>single_matrix[&#39;new_title_subtitle&#39;] = new_titles_sub</pre><p>Finally, we are going to lemmatise words in the sentences. Lemmatisation transforms the word to its meaningful root form taking into consideration the context. Frequently stemming is used as a computationally faster alternative, however less accurate one. Once again we use <em>nltk </em>to lemmatise words</p><pre>nltk.download(&#39;wordnet&#39;)<br>nltk.download(&#39;words&#39;)<br>from nltk.stem import WordNetLemmatizer<br>wordnet_lemmatizer = WordNetLemmatizer()</pre><pre>new_titles_sub = []<br>for title_sub in single_matrix[&#39;title_subtitle&#39;]:<br>    new_title_sub = []<br>    for w_title in title_sub:<br>        new_title_sub.append(wordnet_lemmatizer.lemmatize(w_title, pos=&quot;v&quot;))<br>    new_titles_sub.append(new_title_sub) <br>    <br>single_matrix[&#39;new_title_subtitle&#39;] = new_titles_sub<br>single_matrix[&#39;new_title_subtitle&#39;] = [&#39; &#39;.join(i) for i in single_matrix[&#39;new_title_subtitle&#39;]]</pre><p>Let’s look how the sentences look like after all the transformations</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*p0x3CO_Ht3kenuBm9D0WzA.png" /></figure><h4>How to vectorise text data using TF-IDF?</h4><p>TF-IDF stands for term frequency-inverse document frequency and it is <em>a numerical measure of how relevant a keyword is to a document in some specific set of documents. </em>It is commonly used in text analysis, some of the examples include content ranking and information retrieval.<a href="https://www.researchgate.net/publication/326425709_Text_Mining_Use_of_TF-IDF_to_Examine_the_Relevance_of_Words_to_Documents"> Here</a> is quite a useful paper that talks about the approach in more detail.</p><p>As a name suggests the measure consists of two parts, one that finds frequency of a word appearing in a document (TF) and another the extent of word uniqueness in a corpus (IDF). Let’s look at the simplified version the formula and its components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KV32M2QtGdmGd2c4Y83BsQ.png" /></figure><p>We can see that words appearing more frequently will result in a lower TF-IDF score and for rare words the score will be higher. This weight adjustment is quite important, since overused words will have no additional meaning.</p><p>The easiest way to understand the calculations is by example, in our data set a single title is a document and all the titles form a corpus (set of documents). Consider the word <em>‘create’</em> in the title <em>‘use variables qlikview create powerful data stories’,</em> the document has 7 words and <em>‘create’</em> appears only once, so <em>TF(create) = 1/7</em>. The total number of articles in one of the data sources is <em>12963</em> and word <em>‘create’</em> appears in <em>268 </em>titles so <em>IDF(create)=log(12963/268) =3.88</em>. Thus, <em>TF-IDF =0.14*3.88 = 0.55 </em>is the score for the word <em>‘create’</em>.</p><p>Now that we know how the scores are calculated for each word in a document, we can vectorise the data set with articles titles and subtitles. For this we will use <em>sklearn</em> library in Python, in particular<em> TfidfVectorize</em>r function.</p><p>Note:<a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfTransformer.html#sklearn.feature_extraction.text.TfidfTransformer"> <em>TfidfVectorize</em>r</a> uses a slightly different formula than the one specified above, it adds 1 to IDF. This is done to ensure that the words that appear in every document are not neglected.</p><pre>from sklearn.feature_extraction.text import TfidfVectorizer</pre><pre>tf = TfidfVectorizer(analyzer=&#39;word&#39;, ngram_range=(1, 3), min_df=0)</pre><pre>tfidf_matrices = []<br>data_sets = []<br>for source in [&#39;avd&#39;, &#39;tai&#39;, &#39;tds&#39;]:<br>    source_data = single_matrix[single_matrix[&#39;source&#39;] == source].drop_duplicates()<br>    data_sets.append(source_data[&#39;new_title_subtitle&#39;])<br>    tfidf_matrices.append(tf.fit_transform(<br>source_data[&#39;new_title_subtitle&#39;]))</pre><p>We introduced the for loop that iterates through the data sources, this is done to improve computational time. This will also be needed when looking at the distances between all pairs of sentences and partitioning them into groups. The output is the sparse matrix, where rows are documents and columns all unique words in a corpus.</p><p>Now that we have vectorised titles and subtitles, we can <strong>calculate pairwise distances between all the sentences. </strong>We will use <strong>cosine similarity</strong> between pairs of vectors that represent sentences. The measure considers the angle between two vectors and commonly used in text analysis. Some good explanations of the chosen similarity measure can be found <a href="https://www.sciencedirect.com/topics/computer-science/cosine-similarity#:~:text=Cosine%20similarity%20measures%20the%20similarity,of%20an%20inner%20product%20space.&amp;text=It%20is%20often%20used%20to,or%20phrase%20in%20the%20document.">here</a>, the paper not only provides clear definition it also discusses context based uses.</p><p>We used <em>sklearn </em>library to calculate pairwise cosine similarities, yet again splitting by the source.</p><pre>from sklearn.metrics.pairwise import linear_kernel<br>matrix_with_cos_sim = []<br>for m in tfidf_matrices:<br>    matrix_with_cos_sim.append(linear_kernel(m, m))</pre><p>The output for each data source is a numpy array (NxN) with pairwise similarities between all sentences where N is number of titles/subtitles for a single data source.</p><h4>How to group similar sentences using network graphs?</h4><p>Our aim is to find clusters that have articles covering similar data science topics, to achieve this we will start by building a weighted graph where nodes are articles and edges are their cosine similarity. We are then able to create clusters by applying graph partitioning with the goal to find meaningful subgraphs (also called communities) without imposing a number of communities.</p><p>We will use Python libraries <em>networkx</em> and <em>community</em> to build and partition the graph. Before we proceed with building the graph, we will only select top 15 similar titles for every document in a corpus, the number was chosen based on the measure called modularity which gives indications how good partition is. This approach not only sharpens the graph but also helps with computational speed.</p><pre>import numpy as np<br>from tqdm import tnrange<br>top_n_sentences = []<br>for cs, t in zip(matrix_with_cos_sim, data_sets):<br>    no_dups = np.array(t)<br>    i = 0<br>    top_frame = []<br>    for c, z in zip(cs, tnrange(len(cs))):<br>        # Create vector of titles<br>        start_name = pd.Series([no_dups[i]]*15) <br>        # Index of top 15 similar titles<br>        ix_top_n = np.argsort(-c)[0:15]<br>        cos_sim = pd.Series(c[ix_top_n])<br>        names = pd.Series(no_dups[ix_top_n])<br>        i +=1<br>        top_frame.append(pd.DataFrame([start_name, names, cos_sim]).transpose())<br>    <br>    top_frame = pd.concat(top_frame)<br>    top_frame.columns = [&#39;title1&#39;, &#39;title2&#39;, &#39;cos_sim&#39;]<br>    # Remove the similarities for the same sentences<br>    top_frame[&#39;is_same&#39;] = [bool(i==j) for i, j in zip(top_frame[&#39;title1&#39;], top_frame[&#39;title2&#39;])]<br>    top_frame = top_frame[top_frame[&#39;is_same&#39;] != True]<br>        <br>    top_n_sentences.append(top_frame)</pre><p>The script produces the data frame with top 15 similar titles for every title in the data set (split by source), it will be used as an input to building the graph. Let’s look at the example of the data frame for one of the sources</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*onNRGNWfJ_TiwrY8jTH8OA.png" /></figure><p>We will continue by building and partitioning the graph, we will do it for the source that has the second largest number of articles which is Analytics Vidhya. The snippets of code can be applied to all the sources covered in this article.</p><pre># We start by defining the structure of the graph</pre><pre>top_frame = top_n_sentences[2] #TDS articles</pre><pre>edges = list(zip(top_frame[&#39;title1&#39;], top_frame[&#39;title2&#39;]))<br>weighted_edges = list(zip(top_frame[&#39;title1&#39;], top_frame[&#39;title2&#39;], top_frame[&#39;cos_sim&#39;]))<br>nodes = list(set(top_frame[&#39;title1&#39;]).union(set(top_frame[&#39;title2&#39;])))</pre><p>We now can use<em> networkx</em> to build the graph using structure defined above</p><pre>import networkx as nx<br>G = nx.Graph()<br>G.add_nodes_from(nodes)<br>G.add_edges_from(edges)<br>G.add_weighted_edges_from(weighted_edges)</pre><p>Next we partition the graph using <em>community</em> library, before module imports ensure to install <em>python-louvain</em> library to avoid errors.</p><pre># !pip install python-louvain</pre><pre>import community<br>partition = community.best_partition(G)<br>modularity = community.modularity(partition, G)</pre><p>Earlier we mentioned modularity, the measure how good the partition is, the value in this case is <em>0.7</em>. Usually, values above <em>0.6</em> considered to be decent enough partitioning.</p><pre># Takes some time for larger graphs<br>import matplotlib.pyplot as plt<br>pos = nx.spring_layout(G, dim=2)<br>community_id = [partition[node] for node in G.nodes()]<br>fig = plt.figure(figsize=(10,10))<br>nx.draw(G, pos, edge_color = [&#39;silver&#39;]*len(G.edges()), cmap=plt.cm.tab20,<br>        node_color=community_id, node_size=150)</pre><p>The code above produces the graph and communities we just found, although the plot looks quite busy we are still able to see quite a few clusters found by the approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fGM6vY0QSYjEjPxDsuyYaQ.png" /><figcaption>Titles and subtitles partitioned into communities</figcaption></figure><p>Before we look into clusters in more detail, we are going to transform <em>partition</em> variables we created earlier to a more readable format.</p><pre>title, cluster = [], []<br>for i in partition.items():<br>    title.append(i[0])<br>    cluster.append(i[1])<br>    <br>frame_clust = pd.DataFrame([pd.Series(title), pd.Series(cluster)]).transpose()<br>frame_clust.columns = [&#39;Title&#39;, &#39;Cluster&#39;]</pre><p>The output of the code above is the data frame with all the titles and subtitles and the community they belong to with 45 clusters identified by partitioning the graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*L9GG4VG7z4xlkxlJBMTY6g.png" /><figcaption>Titles and subtitles partitioned into communities</figcaption></figure><p>Now that we have obtained clusters, we can create summary statistics for each of them to understand if any of them have more activity. We will merge the data set that has partitions with the data set that has claps and responses then we will calculate min, max, mean, median and number of articles for each group. Although mainly will focus on median, since we saw earlier that the data is skewed towards smaller values and has outliers present.</p><pre>avd = single_matrix[single_matrix[&#39;source&#39;] ==           &#39;avd&#39;].drop_duplicates()</pre><pre>frame_clust = frame_clust.merge(tds[[&#39;Title&#39;, &#39;new_title_subtitle&#39;, &#39;Claps&#39;, &#39;Responses&#39;]], how=&#39;left&#39;, left_on=&#39;Title&#39;, right_on=&#39;new_title_subtitle&#39;)</pre><pre>grouped_mat = frame_clust.groupby(&#39;Cluster&#39;).agg(<br>{&#39;Claps&#39;: [&#39;max&#39;, &#39;mean&#39;, &#39;sum&#39;, &#39;median&#39;],<br> &#39;Responses&#39;: [&#39;max&#39;, &#39;mean&#39;, &#39;sum&#39;, &#39;median&#39;], <br> &#39;Title_x&#39;: &#39;count&#39;}).reset_index()</pre><pre>grouped_mat.columns = [&#39;cluster&#39;, &#39;claps_max&#39;, &#39;claps_mean&#39;,  &#39;claps_sum&#39;, &#39;claps_median&#39;,&#39;responses_max&#39;, &#39;responses_mean&#39;, &#39;responses_sum&#39;, &#39;responses_median&#39;, &#39;title_count&#39;]</pre><pre>grouped_mat = grouped_mat.sort_values(by = [&#39;claps_median&#39;, &#39;title_count&#39;])</pre><p>For representation purposes will only look at three communities with lowest reader activity and three with highest. We first consider the data set and then we are going to visualise word cloud to determine the common topic in each group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7MzakK0T2uiARy1vuiRrKQ.png" /><figcaption>Communities wit lowest and highest reader activity</figcaption></figure><p>The table above shows that there groups are not very large, let’s see what are the common themes in each cluster we will use wordcloud library for this.</p><pre>from wordcloud import WordCloud<br>fig, ax = plt.subplots(1, 3, figsize=(12.5,6.5))</pre><pre>clusters = [19, 39, 38] #lowest activity groups<br># clusters = [43, 28, 7] #highest activity groups</pre><pre>for cluster, col in zip(clusters, [0, 1, 2]):<br>    corpus = &#39; &#39;.join(frame_clust[&#39;new_title_subtitle&#39;].  [frame_clust[&#39;Cluster&#39;] == cluster])<br>    ax[col].imshow(WordCloud(width = 800,<br>                             height = 800,<br>                             background_color =&#39;white&#39;, <br>                             min_font_size = 10).generate(corpus))<br>    ax[col].axis(&quot;off&quot;)</pre><pre>plt.show()</pre><p>We first look at the communities with lowest activity, it seems that cluster 19 has mostly articles that belong to one author which would explain lower activity. The other two clusters consist of more articles that were written by multiple authors. Quite interestingly we can observe that topics such as ‘object oriented programming in python’ and ‘fraud detection’ attracted least interest from the readers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ro18Oy7xPIHGGdKEB1KddQ.png" /><figcaption>Clusters with lower readers activity</figcaption></figure><p>Moving on to the clusters with highest activity the highlighted topics that cause more interest from the readers are natural language processing, neural networks, activation functions and support vector machines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ix82_6jVviSdPAxuXCE12A.png" /><figcaption>Clusters with higher reader activity</figcaption></figure><p><strong>Wrap up</strong></p><p>Although we were able to establish common themes in low and high readers activity groups, we still observed articles that didn’t have many claps and responses as well as ones that had high activity in each group. The analysis can come handy when trying to establish general patterns of what readers are interested in, as well as the topics that have higher saturation of articles. However choosing a relevant topic doesn’t guarantee success of the article, as many other important factors contribute towards gaining attraction from the reader.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fb70627a4e0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-cluster-similar-sentences-using-tf-idf-and-graph-partitioning-in-python-5fb70627a4e0">How to cluster similar sentences using TF-IDF and Graph partitioning in Python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to scrape articles from data science publications using Python]]></title>
            <link>https://medium.com/analytics-vidhya/what-data-science-articles-attract-more-attention-part-1-efe8faf209d0?source=rss-a66fcb410541------2</link>
            <guid isPermaLink="false">https://medium.com/p/efe8faf209d0</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[TU]]></dc:creator>
            <pubDate>Sun, 17 Jan 2021 10:43:35 GMT</pubDate>
            <atom:updated>2021-01-21T10:04:54.483Z</atom:updated>
            <content:encoded><![CDATA[<h4>What data science articles attract more attention (Part 1)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3ybGLlbePGudkiPB" /><figcaption>Photo by <a href="https://unsplash.com/@miracleday?utm_source=medium&amp;utm_medium=referral">Elena Mozhvilo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Have you ever wondered, what makes an article great?</em> <em>Are there specific areas in data science world readers more interested in? I certainly did!</em> I am aiming to find answers to these questions by analysing articles from data science publications on Medium. The series of articles will cover areas such as web scraping, cleansing text data and topic modelling.</p><p>In the part 1 of the series we will obtain historical articles from various data science publications by means of web scraping using Python.</p><h4><strong>Data science publications</strong></h4><p>There are quite a few publications on Medium that cover topics like data science and programming. We will obtain articles from three publications, <a href="https://towardsdatascience.com/">TDS</a>, <a href="https://medium.com/towards-artificial-intelligence">Towards AI</a> and <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a>. This should provide large enough data set for our future analysis.</p><p><strong><em>Navigating to archives</em></strong></p><p>By the means of simple google search we can get the link for the archive of publication we are interested in. Almost all publications have the url of the following form ‘https://medium.com/publication-name/archive’ with the exception of TDS. However the layout of the page remains unchanged.</p><p>Let’s inspect archive pages of publications, on top of the page we can find years when articles were published, by clicking on one of the years we will see months and similarly to get days we need to click on specific month. Now, <em>one thing to note is that not all years have months and not all months have days</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l3nRhYNBTDg35peZqVZYMg.png" /><figcaption><a href="https://towardsdatascience.com/archive">https://towardsdatascience.com/archive</a></figcaption></figure><h4>How do we get links to all the dates?</h4><p>We start by inspecting the archive page, we can see that the links are stored in <em>‘div’</em> container with class <em>‘timebucket…’</em>. The only difference in naming convention of class for three containers is the width.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*61hcbpUHXBXfMczo-AfhzA.png" /><figcaption>Inspecting <a href="https://medium.com/analytics-vidhya/archive">Analytics Vidhya</a> archive page.</figcaption></figure><p>Now that we have all information needed to obtain the links we can write the code. Let’s start with the imports necessary for this task, we will use Python libraries requests and BeautifulSoup to make HTTP requests and extract the data from HTML.</p><pre>from bs4 import BeautifulSoup<br>import requests</pre><p>Next we define function called <strong><em>get_all_links</em></strong> it uses url of publication archive as an input and returns links for all the dates. It is split into three parts — get years, get months and get days. In the code we also have additional variables such as <em>years_no_months</em> and <em>all_links_no_days</em>, they are there to collect links for the years that didn’t have months and for months that didn’t have days.</p><pre>def get_all_links(url):<br>    &#39;&#39;&#39;function to obtain all the links to archive pages&#39;&#39;&#39;<br>    # url - url to publication archive<br>    r = requests.get(url)<br>    # get years<br>    soup = BeautifulSoup(r.text, &#39;html.parser&#39;)<br>    search = soup.find_all(&#39;div&#39;, class_=&#39;timebucket u-inlineBlock u-width50&#39;)<br>    years = []<br>    for h in search:<br>        years.append(h.a.get(&#39;href&#39;))<br> <br>    # get months <br>    years_months = []<br>    years_no_months = [] # for the years that don&#39;t have months<br>    for year in years:<br>        y_soup =BeautifulSoup(requests.get(year).text,&#39;html.parser&#39;)<br>        search_months = y_soup.find_all(&#39;div&#39;, class_=&#39;timebucket u-inlineBlock u-width80&#39;)<br>        months = []<br>        if search_months:<br>            for month in search_months:<br>                try:<br>                    months.append(month.a.get(&#39;href&#39;))<br>                except:<br>                    pass<br>            years_months.append(months)<br>        else:<br>            years_no_months.append(year)</pre><pre>years_months = [item for sublist in years_months for item in sublist] <br>    <br>    # get days<br>    all_links = []<br>    all_links_no_days = [] # for the month that don&#39;t have days<br>    for month_url in years_months:<br>        m_soup = BeautifulSoup(requests.get(month_url).text, &#39;html.parser&#39;)<br>        all_days = m_soup.find_all(&#39;div&#39;, class_=&#39;timebucket u-inlineBlock u-width35&#39;)<br>        days = []<br>        if all_days:<br>            for day in all_days:<br>                try:<br>                    days.append(day.a.get(&#39;href&#39;))<br>                except:<br>                    pass<br>            all_links.append(days)<br>        else:<br>            all_links_no_days.append(month_url)    <br>    all_links = [item for sublist in all_links for item in sublist]<br>    final_links = years_no_months+all_links_no_days+all_links<br>    return final_links</pre><pre>towards_ai_links = get_all_links(&#39;<a href="https://medium.com/towards-artificial-intelligence/archive&#39;">https://medium.com/towards-artificial-intelligence/archive&#39;</a>)</pre><p>The final output is a list of links to all the pages in the publication archive.</p><pre>[&#39;https://medium.com/towards-artificial-intelligence/archive/2015&#39;, ...]</pre><h4>How do we get data for individual articles?</h4><p>Inspecting the page is a good starting point for this task as well. All article boxes have standard format, thus obtaining information on one box will allow us to collect everything we need on all other articles.</p><p>Before we can write the code we need to establish elements and their classes where information we need is stored. At this point we are only interested to get title, subtitle, number of claps and responses for each article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jA59l80Nputabv4gVT-gaw.png" /><figcaption>Inspecting individual articles</figcaption></figure><p>We now have all the information to write the code, we start with smaller snippets of the main script. To get all the articles from the single link, we search for ‘div’ containers with class ‘streamItem …’.</p><pre>link = &#39;https://medium.com/towards-artificial-intelligence/archive/2015&#39;</pre><pre>soup_ = BeautifulSoup(requests.get(link).text, &#39;html.parser&#39;)<br>articles = soup_.find_all(&#39;div&#39;, class_=&#39;streamItem streamItem--postPreview js-streamItem&#39;)</pre><p>Next we obtain title and subtitle for a single article, in the code below we have two elements for the title <em>‘h3’</em> and <em>‘h2’</em>, this is due to some authors choosing a <em>different approach to writing the title</em>. For the case where the title or subtitle is missing we set it to be empty, however the value can be changed to anything.</p><pre>article = articles[0] #get single article<br>if article.h3:<br>    title = article.h3.getText()<br>elif article.h2:<br>      title = article.h2.getText()<br>else:<br>    title = &#39;&#39;</pre><pre>if article.h4:<br>    subtitle = article.h4.getText()<br>else:<br>    subtitle = &#39;&#39;</pre><p>To obtain claps and responses we find corresponding elements with their class, in this case we are not just interested in text we need to get integer values. At times claps for individual articles reach thousands, in this circumstance they are expressed in following form ‘1k’, ‘2.2k’ and etc, to deal with this we replace ‘K’ with empty entry, transform string to integer and multiply it by 1000. For all the other values we either transform it to integer or set it to zero.</p><p>When an article has some responses from the readers, they come in the following format ‘1 response’, ‘2 responses’ and etc. So here, we just want to obtain the integer, we do so by searching <em>‘\d+’ </em>regular expression in the string.</p><pre>import re<br>s_clap =article.find(&#39;button&#39;, class_=&#39;button button--chromeless u-baseColor--buttonNormal js-multirecommendCountButton u-disablePointerEvents&#39;)<br>if s_clap:<br>    s_clap = s_clap.getText()<br>    if &#39;K&#39; in s_clap:<br>         clap = int(float(s_clap.replace(&#39;K&#39;, &#39;&#39;)))*1000<br>    else:<br>        clap = int(s_clap)       <br>else:<br>    clap = 0</pre><pre>s_response = article.find(&#39;a&#39;, class_=&#39;button button--chromeless u-baseColor--buttonNormal&#39;)<br>if s_response:<br>    s_response = s_response.getText()<br>    response =int(re.search(r&#39;\d+&#39;, s_response).group()))<br>else:<br>    response = 0</pre><p>Now we integrate all the snippets of code into one function called <strong><em>get_data_all_articles</em></strong>, its main argument is the output of <strong><em>get_all_links</em></strong> function we covered earlier (links to all archive pages of the single publications).</p><pre>from tqdm import tnrange #to keep track of the progress <br>import pandas as pd<br>import re</pre><pre>def get_data_all_articles(final_links):<br>    titles, sub_titles, claps, responses = [], [], [], []<br><br>    for link, z in zip(final_links, tnrange(len(final_links))):<br>        soup_ =BeautifulSoup(requests.get(link).text, &#39;html.parser&#39;)<br>        articles = soup_.find_all(&#39;div&#39;, class_=&#39;streamItem streamItem--postPreview js-streamItem&#39;)<br>        title, subtitle, clap, response = [], [], [], []<br>        for article in articles:<br>            if article.h3:<br>                title.append(article.h3.getText())<br>            elif article.h2:<br>                title.append(article.h2.getText())<br>            else:<br>                title.append(&#39;&#39;)</pre><pre>            if article.h4:<br>                subtitle.append(article.h4.getText())<br>            else:<br>                subtitle.append(&#39;&#39;)</pre><pre>            s_clap =article.find(&#39;button&#39;, class_=&#39;button button--chromeless u-baseColor--buttonNormal js-multirecommendCountButton u-disablePointerEvents&#39;)<br>            if s_clap:<br>                s_clap = s_clap.getText()<br>                if &#39;K&#39; in s_clap:<br>                    clap.append(int(float(s_clap.replace(&#39;K&#39;, &#39;&#39;)))*1000)<br>                else:<br>                    clap.append(int(s_clap))              <br>            else:<br>                clap.append(0)<br>            s_response = article.find(&#39;a&#39;, class_=&#39;button button--chromeless u-baseColor--buttonNormal&#39;)<br>            if s_response:<br>                s_response = s_response.getText()<br>                response.append(int(re.search(r&#39;\d+&#39;, s_response).group()))<br>            else:<br>                response.append(0)<br>        titles.append(title)<br>        sub_titles.append(subtitle) <br>        claps.append(clap)<br>        responses.append(response) <br>    titles = [item for sublist in titles for item in sublist]<br>    sub_titles = [item for sublist in sub_titles for item in sublist]<br>    claps = [item for sublist in claps for item in sublist]<br>    responses = [item for sublist in responses for item in sublist]<br>    frame = pd.DataFrame([titles, sub_titles, claps, responses]).transpose()<br>    frame.columns = [&#39;Title&#39;, &#39;Subtitle&#39;, &#39;Claps&#39;, &#39;Responses&#39;]<br>    return frame</pre><pre>data_set = get_data_all_articles(towards_ai_links)</pre><p>Running the script might take some time depending on the number of HTTP requests, each page contains 10 articles and some publications have quite large archives. The script includes <em>tqdm</em> package to keep track of the progress.</p><p>After running the script we get following data set</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xvspjF1U_uU7arkrCxKQ-w.png" /><figcaption>Final data set for <a href="https://medium.com/towards-artificial-intelligence">Towards AI</a> publication</figcaption></figure><p><strong>Wrap up</strong></p><p>We started our journey on uncovering what areas in data science are more interesting to the reader by obtaining the data set from the archives of some of the publications. The information on the article is not limited to the features we covered, there are plenty more metrics to obtain, such as whether an author had an image, how long is the article and etc. Which can be done in the similar fashion to obtaining title, subtitle, claps and responses.</p><p>Keep an eye for further articles in this series were we continue with data cleansing and topic modelling.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efe8faf209d0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/what-data-science-articles-attract-more-attention-part-1-efe8faf209d0">How to scrape articles from data science publications using Python</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimising pairwise Euclidean distance calculations using Python]]></title>
            <link>https://medium.com/data-science/optimising-pairwise-euclidean-distance-calculations-using-python-fc020112c984?source=rss-a66fcb410541------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc020112c984</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[euclidean-distance]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[TU]]></dc:creator>
            <pubDate>Sun, 10 Jan 2021 11:05:40 GMT</pubDate>
            <atom:updated>2021-01-11T13:19:07.028Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Exploring ways of calculating the distance in hope to find the high-performing solution for large data sets</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lOvuwC9KCkpr1KF3" /><figcaption>Photo by <a href="https://unsplash.com/@cadop?utm_source=medium&amp;utm_medium=referral">Mathew Schwartz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Euclidean distance is one of the most commonly used metric, serving as a basis for many machine learning algorithms. However when one is faced with very large data sets, containing multiple features, the simple distance calculation becomes a source of headaches and memory errors.</p><p>Although being aware that packages like SciPy provide robust solution, I couldn’t resist to explore other ways of calculating the distance in hope to find the high-performing approach for large data sets.</p><h4>So, what is Euclidean distances?</h4><p>We begin with quick reminder of the formula, which is quite straightforward. Given two vectors <strong>x</strong> and <strong>y</strong>, we take a square root of the sum of squared differences in their elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*9LeaMTcOXxeTPN-VCbKloQ.png" /></figure><h4>So, why do we get memory errors?</h4><p>This question comes up a lot when dealing with extremely large data sets… Now, let’s say we have 1k vectors for which we need to calculate pairwise distances. This would result in the output matrix with 1m entries, meaning that for larger volumes of data you are very likely to run out of memory.</p><p>For all the computations Python uses local memory, as well as it does not give back allocated memory straightaway. This implies that you are bounded by the specs of your computer. Working in cloud services can help to scale the memory accordingly, however in most of the cases you would still have to parallelise computations.</p><p>Although memory limitation is not going anywhere, it is desirable to have optimised script.</p><p>On to the calculations…</p><h4>Data set: credit card customers</h4><p>For the task of testing the performance of different approaches to calculating the distance, I needed fairly large data set. The data set is available on Kaggle and can be dowloaded using link below.</p><p><a href="https://www.kaggle.com/sakshigoyal7/credit-card-customers">Credit Card customers</a></p><p>Some of the features in the data set aren’t so useful in this case, so we will be using the reduced set.</p><pre>import pandas as pd<br>cc_customers = pd.read_csv(&#39;BankChurners.csv&#39;)<br>cc_customers = cc_customers[[&#39;CLIENTNUM&#39;, &#39;Attrition_Flag&#39;, &#39;Customer_Age&#39;, &#39;Gender&#39;,&#39;Dependent_count&#39;, &#39;Education_Level&#39;, &#39;Marital_Status&#39;,&#39;Income_Category&#39;, &#39;Card_Category&#39;, &#39;Months_on_book&#39;,&#39;Total_Relationship_Count&#39;,&#39;Months_Inactive_12_mon&#39;,&#39;Contacts_Count_12_mon&#39;, &#39;Credit_Limit&#39;, &#39;Total_Revolving_Bal&#39;, &#39;Total_Trans_Amt&#39;,&#39;Total_Trans_Ct&#39;]]</pre><p>We have mixed-type data set that represents information on individual customers with demographic and credit card related attributes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sfeAH4MwgzmFbUoX6inNpA.png" /><figcaption>Some of the features in the customer credit card data</figcaption></figure><p>Before we can use the data as an input, we need to ensure we transform categorical variables to numeric.</p><pre>cat_col = [&#39;Attrition_Flag&#39;, &#39;Gender&#39;, &#39;Education_Level&#39;, &#39;Marital_Status&#39;, &#39;Income_Category&#39;, &#39;Card_Category&#39;]<br>for col in cat_col:<br>    cc_customers[col]=cc_customers[col].astype(&#39;category&#39;).cat.codes</pre><p>When dealing with large data sets, feature transformation is quite important aspect to consider, it can help to reduce the amount of memory used by the matrix (not only). Let’s look at the memory breakdown for the data frame before and after transformations take place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*STpZ_2xgNzVdTZ7CsoZpkw.png" /><figcaption>Memory usage comparison before and after transforming variables.</figcaption></figure><p>Once we transformed the categorical variables to numeric we can see that the memory usage reduced quite substantially.</p><p>Now that we are done with the basic transformations, we can return to our goal which is calculating pairwise Euclidean distances barring in my mind the speed of computation. We have 10127 unique customers, this would result in matrix 10127x10127 dimension.</p><h4>Main script</h4><p>To understand how the code scales with larger data sets, for loop was introduced where at each iteration we consider larger random sample from the original data. We start with 10% from the data and each step our sample increases by 10%, when it comes to the performance time of the code we take average of 20 runs.</p><p>The code below was used for every approach, the only differences would be the distance function.</p><pre>import numpy as np<br>import time<br>from tqdm import tqdm_notebook as tqdm</pre><pre>input_data = cc_customers.drop(&#39;CLIENTNUM&#39;, axis=1) # drop the customer ID<br>iter_times = []<br>for l,z in zip(range(0, 20), tqdm(range(0, 20))):<br>    times = []<br>    for r in np.arange(0.1, 1.1, 0.1):<br>        data_reduced = input_data.sample(frac=r, random_state=1)<br>        tic = time.perf_counter()<br>        ###INSERT DISTANCE CALCULATIONS###<br>        toc = time.perf_counter()<br>        times.append(toc-tic)<br>    iter_times.append(times)<br>    <br>tot_time = [sum(i)/20 for i in zip(*iter_times)]<br>data_size = [len(input_data.sample(frac=r, random_state=1)) for r in np.arange(0.1, 1.1, 0.1)]</pre><pre>for i, j in zip(tot_time, data_size):<br>    print(f&quot;# of customers {j}: {i:0.4f} seconds&quot;)</pre><h4>Method 1: Python packages (SciPy and Sklearn)</h4><p>Using python packages might be a trivial choice, however since they usually provide quite good speed, it can serve as a good baseline.</p><pre>from scipy.spatial.distance import cdist<br>from sklearn.metrics.pairwise import euclidean_distances<br>scipy_cdist = cdist(data_reduced, data_reduced, metric=&#39;euclidean&#39;)<br>sklearn_dist = euclidean_distances(data_reduced, data_reduced)</pre><p>Quite interestingly, Sklearn euclidean_distances outperformed SciPy cdist, with the differences in time becoming more noticeable with larger data sets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*i41tXgHUtIiQIdRZ-9IsZA.png" /><figcaption>cdist vs. euclidean_distances</figcaption></figure><p>Difference in implementation can be a reason for better performance of Sklearn package, since it uses vectorisation trick for computing the distances which is more efficient. Meanwhile, after looking at the source code for cdist implementation, SciPy uses double loop.</p><h4>Method 2: single for loop</h4><p>Optimisation and for loops aren’t usually best friends! However when it comes to pairwise distances…can be difficult to avoid, unless going the vectorisation route (implementation presented later in the article).</p><pre># Without pre-allocating memory<br>dist = []<br>for i in range(len(data_reduced)):<br>    dist.append(((data_reduced- data_reduced[i])**2).sum(axis=1)**0.5)<br>    <br># pre-allocating memory<br>D = np.empty((len(data_reduced),len(data_reduced)))<br>for i in range(len(data_reduced)):<br>    D[i, :] = ((data_reduced-data_reduced[i])**2).sum(axis=1)**0.5<br>return D</pre><p>We compared two approaches, with and without pre-allocating memory before calculating the distance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*0oOSD4KjZdZfk-cMxj7WIQ.png" /></figure><p>It comes to no surprise that pre-allocating memory helped improve performance, though the time taken still exceeded Sklearn implementation.</p><p>Despite the slower performance in some cases it still might be preferential to use this approach, as it is capable to handle larger data sets without running out of memory.</p><h4>Method 3: vectorised implementation</h4><p>After reading few research papers online on this topic, I have to say, I was very hopeful about the performance of this approach. As well as seeing performance of Sklearn euclidean_distances, did boost those hopes even higher…</p><pre>import numpy as np<br>x = np.sum(data_reduced**2, axis=1)[:, np.newaxis]<br>y = np.sum(data_reduced**2,    axis=1)<br>xy = np.dot(data_reduced, data_reduced.T)<br>dist = np.sqrt(x + y - 2*xy)</pre><p>The approach comes quite close in time to cdist implementation for smaller data samples, however it doesn’t scale very well. For the largest data sample the time is almost the same as for loop approach without pre-allocating the memory. Unsurprisingly, it didn’t outperform euclidean_distances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*VRt5pCCmSdMmaeNuugAG-Q.png" /></figure><p><strong>Wrap up</strong></p><p>After testing multiple approaches to calculate pairwise Euclidean distance, we found that Sklearn euclidean_distances has the best performance. Since it uses vectorisation implementation, which we also tried implementing using NumPy commands, without much success in reducing computation time.</p><p>Although we yet again showed that in most cases Python modules provide optimal solution, sometimes one would still have to go with different option, depending on the nature of the task.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc020112c984" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/optimising-pairwise-euclidean-distance-calculations-using-python-fc020112c984">Optimising pairwise Euclidean distance calculations using Python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web scraping: Google search results with Selenium and BeautifulSoup]]></title>
            <link>https://medium.com/analytics-vidhya/web-scraping-google-search-results-with-selenium-and-beautifulsoup-4c534817ad88?source=rss-a66fcb410541------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c534817ad88</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[TU]]></dc:creator>
            <pubDate>Tue, 05 Jan 2021 14:21:20 GMT</pubDate>
            <atom:updated>2021-01-07T15:51:29.301Z</atom:updated>
            <content:encoded><![CDATA[<p>More and more frequently data science projects (and not only) require additional data that can be obtained via the means of web scraping. Google search is not an uncommon starting point.</p><p>In this guide we will walk through the script that obtains links from the google search results.</p><p>Let’s start with the imports, to obtain links from top-n pages of google search result, I am using selenium and BeautifulSoup.</p><pre>from bs4 import BeautifulSoup<br>from selenium import webdriver<br>from webdriver_manager.chrome import ChromeDriverManager</pre><p>I am also using webdriver_manager package, which comes quite handy at times. Using this package there is no need to download a web driver to your local machine if you don’t have one, it also helps to avoid manual input of the custom path to a web driver. The package supports most of the browsers.</p><p>Next, we set up some preferences for the web browser. To avoid web browser popping up when you run your code, I use ‘headless’ argument. There are also a handful of other options that allow to customise the web browser to adapt to the task at hand.</p><pre>chrome_options = webdriver.ChromeOptions()<br>chrome_options.add_argument(&quot;--headless&quot;)</pre><p>We can now start the ChromeDriver. First input argument requires a path to the driver, however by means of the webdriver_manager we can use installation instead.</p><pre>driver = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=chrome_options)</pre><p>Once the web driver is set up, we can move on to the main part of the code where we obtain web links for google search results.</p><pre># Query to obtain links<br>query = &#39;comprehensive guide to web scraping in python&#39;<br>links = [] # Initiate empty list to capture final results</pre><pre># Specify number of pages on google search, each page contains 10 #links<br>n_pages = 20 <br>for page in range(1, n_pages):<br>    url = &quot;http://www.google.com/search?q=&quot; + query + &quot;&amp;start=&quot; +      str((page - 1) * 10)<br>    driver.get(url)<br>    soup = BeautifulSoup(driver.page_source, &#39;html.parser&#39;)<br>    # soup = BeautifulSoup(r.text, &#39;html.parser&#39;)<br><br>    search = soup.find_all(&#39;div&#39;, class_=&quot;yuRUbf&quot;)<br>    for h in search:<br>        links.append(h.a.get(&#39;href&#39;))</pre><p>The code requires two inputs, query of interest and the number of pages in google search to go through. Each page contains 10 search results.</p><p>Once parameters are in place we load the url using selenium webdriver, then using BeautifulSoup we parse website data using html.parser. Website data comes in html format, we can view the script behind the website by inspecting the web page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z8F33NV38RBHI8fss5PPJA.png" /></figure><p>We are interested in hyperlinks to the search results which are stored in &lt;div class=’yuRUbf’&gt; container. All elements are found using BeautifulSoup command .find_all() where we specify element and class as an inputs.</p><pre>search = soup.find_all(&#39;div&#39;, class_=&quot;yuRUbf&quot;)</pre><p>For every search result we obtained, we need to extract hyperlink which is stored as href attribute of &lt;a&gt; element.</p><pre>for h in search:<br>        links.append(h.a.get(&#39;href&#39;))</pre><p>We now have all the code blocks required to obtain the links to google search results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bSigVRd2Hc69HkRtIeyibQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c534817ad88" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/web-scraping-google-search-results-with-selenium-and-beautifulsoup-4c534817ad88">Web scraping: Google search results with Selenium and BeautifulSoup</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>