<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/how-to-extract-data-from-a-pdf-file-with-r/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://r-posts.com/how-to-extract-data-from-a-pdf-file-with-r/"> R-posts.com</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>
<img data-orig-file="https://i0.wp.com/r-posts.com/wp-content/uploads/2018/01/R-Data-Mining-Cover.png?fit=810%2C1000" data-orig-size="810,1000" data-medium-file="https://i0.wp.com/r-posts.com/wp-content/uploads/2018/01/R-Data-Mining-Cover.png?fit=243%2C300" data-attachment-id="414" data-image-meta="{" data-image-description="" src="https://i0.wp.com/r-posts.com/wp-content/uploads/2018/01/R-Data-Mining-Cover.png?resize=243%2C300" data-permalink="http://r-posts.com/how-to-extract-data-from-a-pdf-file-with-r/r-data-mining-cover/" data-large-file="https://i0.wp.com/r-posts.com/wp-content/uploads/2018/01/R-Data-Mining-Cover.png?fit=450%2C556" alt="" data-image-title="R-Data-Mining Cover" sizes="(max-width: 243px) 100vw, 243px" width="243" data-comments-opened="1" class="wp-image-414" data-recalc-dims="1" height="300"><em>In this post, taken from the book <a rel="nofollow" href="https://www.packtpub.com/big-data-and-business-intelligence/r-data-mining?utm_source=r-bloggers&utm_medium=referral&utm_campaign=5-dollar-2017" target="_blank">R Data Mining</a> by Andrea Cirillo, we’ll be looking at how to scrape PDF files using R. It’s a relatively straightforward way to look at text mining – but it can be challenging if you don’t know exactly what you’re doing.</em></p>
<p> <strong>Until January 15th, every single eBook and video by <a rel="nofollow" href="https://www.packtpub.com/?utm_source=r-bloggers&utm_medium=referral&utm_campaign=5-dollar-2017" target="_blank">Packt</a> is just $5! Start exploring some of<a rel="nofollow" href="https://www.packtpub.com/tech/R?utm_source=r-bloggers&utm_medium=referral&utm_campaign=5-dollar-2017" target="_blank"> Packt’s huge range of R titles here</a>.
<p> You may not be aware of this, but some organizations create something called a ‘customer card’ for every single customer they deal with. This is quite an informal document that contains some relevant information related to the customer, such as the industry and the date of foundation. Probably the most precious information contained within these cards is the comments they write down about the customers. Let me show you one of them:<br>
<img data-orig-file="https://i2.wp.com/r-posts.com/wp-content/uploads/2018/01/R-data-mining-1.png?fit=1144%2C447" data-orig-size="1144,447" data-medium-file="https://i2.wp.com/r-posts.com/wp-content/uploads/2018/01/R-data-mining-1.png?fit=450%2C176" data-attachment-id="410" data-image-meta="{" data-image-description="" src="https://i2.wp.com/r-posts.com/wp-content/uploads/2018/01/R-data-mining-1.png?resize=450%2C176" data-permalink="http://r-posts.com/how-to-extract-data-from-a-pdf-file-with-r/r-data-mining-1/" data-large-file="https://i2.wp.com/r-posts.com/wp-content/uploads/2018/01/R-data-mining-1.png?fit=450%2C176" alt="" data-image-title="R-data-mining-1" sizes="(max-width: 450px) 100vw, 450px" width="450" data-comments-opened="1" class="wp-image-410" data-recalc-dims="1" height="176">My plan was the following—get the information from these cards and analyze it to discover whether some kind of common traits emerge.</p>
<p> As you may already know, at the moment this information is presented in an unstructured way; that is, we are dealing with unstructured data. Before trying to analyze this data, we will have to gather it in our analysis environment and give it some kind of structure.</p>
<p> Technically, what we are going to do here is called text mining, which generally refers to the activity of gaining knowledge from texts. The techniques we are going to employ are the following:</p>
<ul>
<li>Sentiment analysis</li>
<li>Wordclouds</li>
<li>N-gram analysis</li>
<li>Network analysis</li>
</ul>
<h1>Getting a list of documents in a folder</h1>
<p>First of all, we need to get a list of customer cards we were from the commercial department. I have stored all of them within the ‘data’ folder on my workspace. Let’s use list.files() to get them:</p>
<pre>file_vector &lt;- list.files(path = &quot;data&quot;)</pre>
<p>Nice! We can inspect this looking at the head of it. Using the following command:</p>
<pre>file_vector %>% head()

[1] &quot;banking.xls&quot; &quot;Betasoloin.pdf&quot; &quot;Burl Whirl.pdf&quot; &quot;BUSINESSCENTER.pdf&quot;
 [5] &quot;Buzzmaker.pdf&quot; &quot;BuzzSaw Publicity.pdf&quot;</pre>
<p>Uhm… not exactly what we need. I can see there are also .xls files. We can remove them using the grepl() function, which performs partial matches on strings, returning TRUE if the pattern required is found, or FALSE if not. We are going to set the following test here: give me TRUE if you find .pdf in the filename, and FALSE if not:</p>
<pre>grepl(&quot;.pdf&quot;,file_list)

[1] FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
[18] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
[35] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
[52] TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
[69] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
[86] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
[103] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE TRUE
[120] TRUE</pre>
<p>As you can see, the first match results in a FALSE since it is related to the .xls file we saw before. We can now filter our list of files by simply passing these matching results to the list itself. More precisely, we will slice our list, selecting only those records where our grepl() call returns TRUE:</p>
<pre>pdf_list &lt;- file_vector[grepl(&quot;.pdf&quot;,file_list)]</pre>
<p>Did you understand [grepl(“.pdf”,file_list)] ? It is actually a way to access one or more indexes within a vector, which in our case are the indexes corresponding to “.pdf”, exactly the same as we printed out before.</p>
<p>If you now look at the list, you will see that only PDF filenames are shown on it.</p>
<h2>Reading PDF files into R via pdf_text()</h2>
<p>R comes with a really useful that’s employed tasks related to PDFs. This is named pdftools, and beside the pdf_text function we are going to employ here, it also contains other relevant functions that are used to get different kinds of information related to the PDF file into R.</p>
<p>For our purposes, it will be enough to get all of the textual information contained within each of the PDF files. First of all, let’s try this on a single document; we will try to scale it later on the whole set of documents. The only required argument to make pdf_text work is the path to the document. The object resulting from this application will be a character vector of length 1:</p>
<pre>pdf_text(&quot;data/BUSINESSCENTER.pdf&quot;)

[1] &quot;BUSINESSCENTER business profile\nInformation below are provided under non disclosure agreement. date of enquery: 12.05.2017\ndate of foundation: 1993-05-18\nindustry: Non-profit\nshare holders: Helene Wurm ; Meryl Savant ; Sydney Wadley\ncomments\nThis is one of our worst customer. It really often miss payments even if for just a couple of days. We have\nproblems finding useful contact persons. The only person we can have had occasion to deal with was the\nfiscal expert, since all other relevant person denied any kind of contact.\n                                                       1\n&quot;</pre>
<p>If you compare this with the original PDF document you can easily see that all of the information is available even if it is definitely not ready to be analyzed. What do you think is the next step needed to make our data more useful?</p>
<p>We first need to split our string into lines in order to give our data a structure that is closer to the original one, that is, made of paragraphs. To split our string into separate records, we can use the strsplit() function, which is a base R function. It requires the string to be split and the token that decides where the string has to be split as arguments. If you now look at the string, you’ll notice that where we found the end of a line in the original document, for instance after the words business profile, we now find the \n token. This is commonly employed in text formats to mark the end of a line.</p>
<p>We will therefore use this token as a split argument:</p>
<pre>pdf_text(&quot;data/BUSINESSCENTER.pdf&quot;) %>% strsplit(split = &quot;\n&quot;)

[[1]]
 [1] &quot;BUSINESSCENTER business profile&quot;
 [2] &quot;Information below are provided under non disclosure agreement. date of enquery: 12.05.2017&quot;
 [3] &quot;date of foundation: 1993-05-18&quot;
 [4] &quot;industry: Non-profit&quot;
 [5] &quot;share holders: Helene Wurm ; Meryl Savant ; Sydney Wadley&quot;
 [6] &quot;comments&quot;
 [7] &quot;This is one of our worst customer. It really often miss payments even if for just a couple of days. We have&quot;
 [8] &quot;problems finding useful contact persons. The only person we can have had occasion to deal with was the&quot;
 [9] &quot;fiscal expert, since all other relevant person denied any kind of contact.&quot;
 [10] &quot; 1&quot;</pre>
<p>strsplit() returns a list with an element for each element of the character vector passed as argument; within each list element, there is a vector with the split string.</p>
<p>Isn’t that better? I definitely think it is. The last thing we need to do before actually doing text mining on our data is to apply those treatments to all of the PDF files and gather the results into a conveniently arranged data frame.</p>
<h2>Iteratively extracting text from a set of documents with a for loop</h2>
<p>What we want to do here is run trough the list of files and for filename found there, we run the pdf_text() function and then the strsplit() function to get an object similar to the one we have seen with our test. A convenient way to do this is by employing a ‘for’ loop. These structures basically do this to their content: Repeat this instruction n times and then stop. Let me show you a typical ‘for’ loop:</p>
<pre>for (i in 1:3){
 print(i)
}</pre>
<p>If we run this, we obtain the following:</p>
<pre>[1] 1
 [1] 2
 [1] 3</pre>
<p>This means that the loop runs three times and therefore repeats the instructions included within the brackets three times. What is the only thing that seems to change every time? It is the value of i. This variable, which is usually called counter, is basically what the loop employs to understand when to stop iterating. When the loop execution starts, the loop starts increasing the value of the counter, going from 1 to 3 in our example. The for loop repeats the instructions between the brackets for each element of the values of the vector following the in clause in the for command. At each step, the value of the variable before in (i in this case) takes one value of the sequence from the vector itself.</p>
<p>The counter is also useful within the loop itself, and it is usually employed to iterate within an object in which some kind of manipulation is desired. Take, for instance, a vector defined like this:</p>
<pre>vector &lt;- c(1,2,3)</pre>
<p>Imagine we want to increase the value of every element of the vector by 1. We can do this by employing a loop such as this:</p>
<pre>for (i in 1:3){
 vector[i] &lt;- vector[i]+1
}</pre>
<p>If you look closely at the loop, you’ll realize that the instruction needs to access the element of the vector with an index equal to i and modify this value by 1. The counter here is useful because it will allow iteration on all vectors from 1 to 3.</p>
<p>Be aware that this is actually not a best practice because loops tend to be quite computationally expensive, and they should be employed when no other valid alternative is available. For instance, we can obtain the same result here by working directly on the whole vector, as follows:</p>
<pre>vector_increased &lt;- vector +1</pre>
<p>If you are interested in the topic of avoiding loops where they are not necessary, I can share with you some relevant material on this.</p>
<p>For our purposes, we are going to apply loops to go through the pdf_list object, and apply the pdf_text function and subsequently the strsplit() function to each element of this list:</p>
<pre>corpus_raw &lt;- data.frame(&quot;company&quot; = c(),&quot;text&quot; = c())

for (i in 1:length(pdf_list)){
print(i)
 pdf_text(paste(&quot;data/&quot;, pdf_list[i],sep = &quot;&quot;)) %>% 
 strsplit(&quot;\n&quot;)-> document_text
data.frame(&quot;company&quot; = gsub(x =pdf_list[i],pattern = &quot;.pdf&quot;, replacement = &quot;&quot;), 
 &quot;text&quot; = document_text, stringsAsFactors = FALSE) -> document

colnames(document) &lt;- c(&quot;company&quot;, &quot;text&quot;)
corpus_raw &lt;- rbind(corpus_raw,document) 
}</pre>
<p>Let’s get closer to the loop: we first have a call to the pdf_text function, passing an element of pdf_list as an argument; it is defined as referencing the i position in the list. Once we have done this, we can move on to apply the strsplit() function to the resulting string. We define the document object, which contains two columns, in this way:</p>
<ul>
<li>company, which stores the name of the PDF without the .pdf token; this is the name of the company</li>
<li>text, which stores the text resulting from the extraction</li>
</ul>
<p>This document object is then appended to the corpus object, which we created previously, to store all of the text within the PDF.</p>
<p>Let’s have a look a the resulting data frame:</p>
<pre>corpus_raw %>% head()</pre>
<p><img data-orig-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2018/01/R-data-mining-2.png?fit=815%2C129" data-orig-size="815,129" data-medium-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2018/01/R-data-mining-2.png?fit=450%2C71" data-attachment-id="411" data-image-meta="{" data-image-description="" src="https://i1.wp.com/r-posts.com/wp-content/uploads/2018/01/R-data-mining-2.png?resize=450%2C71" data-permalink="http://r-posts.com/how-to-extract-data-from-a-pdf-file-with-r/r-data-mining-2/" data-large-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2018/01/R-data-mining-2.png?fit=450%2C71" alt="" data-image-title="R-data-mining-2" sizes="(max-width: 450px) 100vw, 450px" width="450" data-comments-opened="1" class="wp-image-411" data-recalc-dims="1" height="71"></p>
<p></p>
<p>This is a well-structured object, ready for some text mining. Nevertheless, if we look closely at our PDF customer cards, we can see that there are three different kinds of information and they should be handled differently:</p>
<p></p>
<ul>
<li>Repeated information, such as the confidentiality disclosure on the second line and the date of enquiry (12.05.2017)</li>
<li>Structured attributes, for instance, date of foundation or industry</li>
<li>Strictly unstructured data, which is in the comments paragraph</li>
</ul>
<p>We are going to address these three kinds of data differently, removing the first group of irrelevant information; we therefore have to split our data frame accordingly into two smaller data frames. To do so, we will leverage the grepl() function once again, looking for the following tokens:</p>
<ul>
<li>12.05.2017: This denotes the line showing the non-disclosure agreement and the date of inquiry.</li>
<li>business profile: This denotes the title of the document, containing the name of the company. We already have this information stored within the company column.</li>
<li>comments: This is the name of the last paragraph.</li>
<li>1: This represents the number of the page and is always the same on every card.</li>
</ul>
<p>We can apply the filter function to our corpus_raw object here as follows:</p>
<pre>corpus_raw %>% 
filter(!grepl(&quot;12.05.2017&quot;,text)) %>% 
filter(!grepl(&quot;business profile&quot;,text)) %>% 
filter(!grepl(&quot;comments&quot;,text)) %>%
filter(!grepl(&quot;1&quot;,text)) -> corpus</pre>
<p>Now that we have removed those useless things, we can actually split the data frame into two sub-data frames based on what is returned by the grepl function when searching for the following tokens, which point to the structured attributes we discussed previously:</p>
<p></p>
<ul>
<li>date of foundation</li>
<li>industry</li>
<li>shareholders</li>
</ul>
<p>
We are going to create two different data frames here; one is called ‘information’ and the other is called ‘comments’:</p>
<pre>corpus %>% 
filter(!grepl(c(&quot;date of foundation&quot;),text)) %>% 
filter(!grepl(c( &quot;industry&quot;),text)) %>% 
filter(!grepl(c( &quot;share holders&quot;),text)) -> comments

corpus %>% 
filter(grepl((&quot;date of foundation&quot;),text)|grepl(( &quot;industry&quot;),text)|grepl(( &quot;share holders&quot;),text))-> information</pre>
<p>As you can see, the two data treatments are nearly the opposite of each other, since the first looks for lines showing none of the three tokens while the other looks for records showing at least one of the tokens.</p>
<p>Let’s inspect the results by employing the head function:</p>
<pre>information %>% head()
comments %>% head()</pre>
<p><img data-orig-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2018/01/R-data-mining-3.png?fit=987%2C295" data-orig-size="987,295" data-medium-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2018/01/R-data-mining-3.png?fit=450%2C134" data-attachment-id="412" data-image-meta="{" data-image-description="" src="https://i1.wp.com/r-posts.com/wp-content/uploads/2018/01/R-data-mining-3.png?resize=450%2C134" data-permalink="http://r-posts.com/how-to-extract-data-from-a-pdf-file-with-r/r-data-mining-3/" data-large-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2018/01/R-data-mining-3.png?fit=450%2C134" alt="" data-image-title="R-data-mining-3" sizes="(max-width: 450px) 100vw, 450px" width="450" data-comments-opened="1" class="wp-image-412" data-recalc-dims="1" height="134"></p>
<p>Great! We are nearly done. We are now going to start analyzing the comments data frame, which reports all comments from our colleagues. The very last step needed to make this data frame ready for subsequent analyzes is to tokenize it, which basically means separating it into different rows for all the words available within the text column. To do this, we are going to leverage the unnest_tokens function, which basically splits each line into words and produces a new row for each word, having taken care to repeat the corresponding value within the other columns of the original data frame.</p>
<p>This function comes from the recent tidytext package by Julia Silge and Davide Robinson, which provides an organic framework of utilities for text mining tasks. It follows the tidyverse framework, which you should already know about if you are using the dplyr package.</p>
<p>Let’s see how to apply the unnest_tokens function to our data:</p>
<pre>comments %>% 
 unnest_tokens(word,text)-> comments_tidy</pre>
<p>If we now look at the resulting data frame, we can see the following:</p>
<p> <img data-orig-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2018/01/r-data-mining-4.png?fit=197%2C123" data-orig-size="197,123" data-medium-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2018/01/r-data-mining-4.png?fit=197%2C123" data-attachment-id="413" data-image-meta="{" data-image-description="" src="https://i1.wp.com/r-posts.com/wp-content/uploads/2018/01/r-data-mining-4.png?resize=197%2C123" data-permalink="http://r-posts.com/how-to-extract-data-from-a-pdf-file-with-r/r-data-mining-4/" data-large-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2018/01/r-data-mining-4.png?fit=197%2C123" alt="" data-image-title="r-data-mining-4" width="197" data-comments-opened="1" class="wp-image-413" data-recalc-dims="1" height="123"></p>
<p>As you can see, we now have each word separated into a single record.</p>
<p> <strong>Thanks for reading! We hope you enjoyed this extract taken from <a rel="nofollow" href="https://www.packtpub.com/big-data-and-business-intelligence/r-data-mining?utm_source=r-bloggers&utm_medium=referral&utm_campaign=5-dollar-2017" target="_blank">R Data Mining</a>.</strong></p>
<p> <strong>Explore <a rel="nofollow" href="https://www.packtpub.com/tech/R?utm_source=r-bloggers&utm_medium=referral&utm_campaign=5-dollar-2017" target="_blank">$5 R eBooks and videos from Packt</a> until January 15th 2018.</strong></p>
<p> </p>
<p>
<img data-orig-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2018/01/5-Graphic.png?fit=828%2C465" data-orig-size="828,465" data-medium-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2018/01/5-Graphic.png?fit=450%2C253" data-attachment-id="415" data-image-meta="{" data-image-description="" src="https://i1.wp.com/r-posts.com/wp-content/uploads/2018/01/5-Graphic.png?resize=450%2C253" data-permalink="http://r-posts.com/how-to-extract-data-from-a-pdf-file-with-r/5-graphic/" data-large-file="https://i1.wp.com/r-posts.com/wp-content/uploads/2018/01/5-Graphic.png?fit=450%2C253" alt="" data-image-title="$5 Graphic" sizes="(max-width: 450px) 100vw, 450px" width="450" data-comments-opened="1" class="wp-image-415" data-recalc-dims="1" height="253"></p></strong>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://r-posts.com/how-to-extract-data-from-a-pdf-file-with-r/"> R-posts.com</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 rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/Da4-F2Y9CpE" height="1"></a></div>