<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/key-phrase-extraction-from-tweets/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://datascienceplus.com/key-phrase-extraction-from-tweets/"> DataScience+</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>In a previous <a target="_blank" rel="nofollow" href="https://datascienceplus.com/analyzing-the-first-presidential-debate/">post</a> of mine published at DataScience+, I analyzed the text of the first presidential debate using relatively simple string manipulation functions to answer some high level questions from the available text.</p>
<p>In this post, we leverage a few other NLP techniques to analyze another text corpus – A collection of tweets. Given a tweet, we would like to extract the key words or phrases which conveys the gist of the meaning of the tweet. For the purpose of this demo, we will extract President Donald Trump’s tweets (~3000 in total) from twitter using Twitter’s API. </p>
<p>I would not cover the twitter data extraction part in this post and directly jump on to the actual analysis (The data extraction code is in Python). However, I have uploaded a csv file with the extracted tweets <a target="_blank" rel="nofollow" href="https://www.dropbox.com/s/qfdnw4drfb7bhiv/tweets_df.csv?dl=0">here</a>. You can download the file to your local machine &amp; load it in your R console if you wish to follow along with the tutorial.</p>
<p>So let’s jump in now to the actual analysis!</p>
<h2>How do we access key phrases from the text</h2>
<p>There are various different approaches that one can try for this. We will try out one specific approach in this post – POS (Part of Speech) tagging followed by pattern based chunking and extraction</p>
<h3>Rationale behind this approach</h3>
<p>Consider the following tweet from our sample:</p>
<blockquote><p>After being forced to apologize for its bad and inaccurate coverage of me after winning the election, the FAKE NEWS @nytimes is still lost!</p>
</blockquote>
<p>A POS tag output for this text would be as follows:</p>
<blockquote><p>After/IN being/VBG forced/VBN to/TO apologize/VB for/IN its/PRP$ bad/JJ and/CC inaccurate/JJ coverage/NN of/IN me/PRP after/IN winning/VBG the/DT election/NN ,/, the/DT FAKE/NNP NEWS/NNP @nytimes/NNP is/VBZ still/RB lost/VBN !/</p>
</blockquote>
<p>A definition of each of these tags can be found <a target="_blank" rel="nofollow" href="https://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html">here</a>.</p>
<p>We can make couple of simple observations from the POS tagged text:</p>
<ul>
<li>As is obvious, certain tags are more informative than others. For. E.g. Noun tags (starting with NN) would carry more information than prepositions or conjunctions. Similarly, if we would like to know “what” is being spoken about, Noun words may be more relevant than others.</li>
<li>Secondly, chunks of words would carry more meaning than looking at individual words in isolation. For e.g. in the text above the word “coverage” alone does not adequately convey the meaning of the text. However, “inaccurate coverage” very nicely captures one of the key themes in this tweet.</li>
</ul>
<h2>How do we implement it</h2>
<p>This is where you may face some challenges, if you are trying to implement this in R. Python seems to be more generally preferred for tasks such as this, with many of the POS tagging &amp; chunking examples that you will find online, based on the NLTK library in Python. While NLTK is great to work with, I tried implementing this in R as well using the openNLP package.</p>
<p>This is the flow that we will follow:</p>
<blockquote><p>Text –> Sentence Annotation –> Word Annotation –> POS Tagging –> Chunking</p>
</blockquote>
<p>Given below is an explanation of the approach:</p>
<h3>Step 1: POS Tagging</h3>
<p>The POS tagging code is pretty much based on the code examples that are given as part of openNLP’s documentation. Here is the code:</p>
<pre>
#We will try the approach for 1 tweet; Finally we will convert this into a function
x &lt;- &quot;the text of the tweet&quot;
x &lt;- as.String(x)
# Before POS tagging, we need to do Sentence annotation followed by word annotation
wordAnnotation &lt;- annotate(x, list(Maxent_Sent_Token_Annotator(), Maxent_Word_Token_Annotator()))

# POS tag the words &amp; extract the &quot;words&quot; from the output
POSAnnotation &lt;- annotate(x, Maxent_POS_Tag_Annotator(), wordAnnotation)
POSwords &lt;- subset(POSAnnotation, type == &quot;word&quot;)
# Extract the tags from the words
tags &lt;- sapply(POSwords$features, '[[', &quot;POS&quot;)

# Create a data frame with words and tags
tokenizedAndTagged &lt;- data.frame(Tokens = x[POSwords], Tags = tags)
</pre>
<h3>Step 2: Chunking and Extraction</h3>
<p>For us to chunk the POS tagged text, we would have to first define what POS pattern we would consider as a chunk. For e.g. an Adjective-Noun(s) combination (JJ-NN) can be a useful pattern to extract (in the example above this pattern would have given us the “inaccurate coverage” chunk). Similarly, we may wish to chunk and extract proper nouns (so for e.g. in this tweet – <i>“ Hope you like my nomination of Judge Neil Gorsuch for the United States Supreme Court. He is a good and brilliant man, respected by all.“</i>, chunking and extracting proper nouns (NNP, NNPS) would give us “Judge Neil Gorsuch” &amp; “United States Supreme Court”)</p>
<p>So once we define what POS pattern we consider as a chunk, the next step is to extract them.<br>
This is a bit trickier (In python’s nltk, there is a very useful function that helps extract chunks from POS tagged text using RegEx based pattern search. I couldn’t find a similar function in openNLP, so I wrote a simple workaround for this function in R)</p>
<p>Given below is the code with explanatory comments:</p>
<pre>
# Define a flag(tags_mod) for pos tags - Flag set to 1 if it contains the POS tag we are interested in else 0
# In this case we only want Noun and Adjective tags (NN, JJ)
# Note that this will also capture variations such as NNP, NNPS etc
tokenizedAndTagged$Tags_mod = grepl(&quot;NN|JJ&quot;, tokenizedAndTagged$Tags)
  
# Initialize a vector to store chunk indexes
chunk = vector()  
  
# Iterate thru each word and assign each one to a group
# if the word doesn’t belong to NN|JJ tags (i.e. tags_mod flag is 0) assign it to the default group (0)
# If the ith tag is in “NN|JJ” (i.e. tags_mod flag is 1) assign it to group i-1 if the (i-1)th tag_mod flag is also 1; else assign it to a new group
chunk[1] = as.numeric(tokenizedAndTagged$Tags_mod[1])
for (i in 2:nrow(tokenizedAndTagged)) {
    
    if(!tokenizedAndTagged$Tags_mod[i]) {
      chunk[i] = 0
    } else if (tokenizedAndTagged$Tags_mod[i] == tokenizedAndTagged$Tags_mod[i-1]) {
      chunk[i] = chunk[i-1]
    } else {
      chunk[i] = max(chunk) + 1
    }
    
 }
</pre>
<p>Finally extract matching pattern</p>
<pre>
# Split and chunk words
text_chunk &lt;- split(as.character(tokenizedAndTagged$Tokens), chunk)
tag_pattern &lt;- split(as.character(tokenizedAndTagged$Tags), chunk)
names(text_chunk) &lt;- sapply(tag_pattern, function(x) paste(x, collapse = &quot;-&quot;))
 
# Extract chunks matching pattern
# We will extract JJ-NN chunks and two or more continuous NN tags 
# &quot;NN.-NN&quot; -> The &quot;.&quot; in this regex will match all variants of NN: NNP, NNS etc
res = text_chunk[grepl(&quot;JJ-NN|NN.-NN&quot;, names(text_chunk))]
</pre>
<p>The overall function is available <a target="_blank" rel="nofollow" href="https://gist.github.com/anup50695/e79c492da3115bbfabfe980d63a02016">here</a>.</p>
<h2>Testing the Approach</h2>
<p>Testing the approach on a few tweets gave fairly promising results.<br>
I am providing below some sample results.</p>
<p><b>Sample Tweet 1:</b></p>
<blockquote><p>“Jeff Sessions is an honest man. He did not say anything wrong. He could have stated his response more accurately, but it was clearly not….”</p>
</blockquote>
<p>Chunking Output:<br>
c(“Jeff Sessions”, “honest man”)</p>
<p><b>Sample Tweet 2:</b></p>
<blockquote><p>Since November 8th, Election Day, the Stock Market has posted $3.2 trillion in GAINS and consumer confidence is at a 15 year high. Jobs!</p>
</blockquote>
<p>Chunking Output:<br>
c(“Election Day”, “Stock Market”)</p>
<p><b>Sample Tweet 3:</b></p>
<blockquote><p>Russia talk is FAKE NEWS put out by the Dems, and played up by the media, in order to mask the big election defeat and the illegal leaks</p>
</blockquote>
<p>Chunking Output:<br>
c(“Russia talk”, “FAKE NEWS”, “big election defeat”, “illegal leaks”)</p>
<h2>Conclusion</h2>
<p>As can be seen, this approach seems to be working fairly well.<br>
The extracted chunks does convey some of the key themes present in the text.<br>
We can offcourse try out more complex techniques &amp; alternate approaches and if time permits, I will try exploring &amp; blogging about a few of them in the future.<br>
However, the intent of this post was to provide readers a quick overview of POS tagging and chunking approaches and the usefulness of these techniques for certain NLP Tasks.</p>
<p>Hope you find this useful!</p>
<ul></ul>
<p><strong>
<p>Related Post</p>
<p>
<ol>
<li><a title="Permanent Link toFinancial time series forecasting – an easy approach" target="_blank" rel="nofollow" href="https://datascienceplus.com/financial-time-series-forecasting-an-easy-approach/">Financial time series forecasting – an easy approach</a></li>
<li><a title="Permanent Link toOutlier detection and treatment with R" target="_blank" rel="nofollow" href="https://datascienceplus.com/outlier-detection-and-treatment-with-r/">Outlier detection and treatment with R</a></li>
<li><a title="Permanent Link toImplementing Apriori Algorithm in R" target="_blank" rel="nofollow" href="https://datascienceplus.com/implementing-apriori-algorithm-in-r/">Implementing Apriori Algorithm in R</a></li>
<li><a title="Permanent Link toR for Publication: Lesson 6, Part 2 – Linear Mixed Effects Models" target="_blank" rel="nofollow" href="https://datascienceplus.com/r-for-publication-by-page-piccinini-lesson-6-part-2-linear-mixed-effects-models-lmem/">R for Publication: Lesson 6, Part 2 – Linear Mixed Effects Models</a></li>
<li><a title="Permanent Link toR for Publication: Lesson 6, Part 1 – Linear Mixed Effects Models" target="_blank" rel="nofollow" href="https://datascienceplus.com/r-for-publication-by-page-piccinini-lesson-6-part-1-linear-mixed-effects-models-lmem/">R for Publication: Lesson 6, Part 1 – Linear Mixed Effects Models</a></li>
</ol></strong>
<div>
<a target="_blank" rel="nofollow" href="http://feeds.feedburner.com/~ff/datascienceplus?a=bgpJ0QhKsAc:9pO5_5zIX3Q:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/datascienceplus?i=bgpJ0QhKsAc:9pO5_5zIX3Q:D7DqB2pKExk" border="0"></a> <a target="_blank" rel="nofollow" href="http://feeds.feedburner.com/~ff/datascienceplus?a=bgpJ0QhKsAc:9pO5_5zIX3Q:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/datascienceplus?d=qj6IDK7rITs" border="0"></a> <a target="_blank" rel="nofollow" href="http://feeds.feedburner.com/~ff/datascienceplus?a=bgpJ0QhKsAc:9pO5_5zIX3Q:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/datascienceplus?d=yIl2AUoC8zA" border="0"></a>
</div>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://datascienceplus.com/key-phrase-extraction-from-tweets/"> DataScience+</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/Gsl0wNft1Ds"></a></div>