How To Download Scientific Papers Using Python UPDATED

How To Download Scientific Papers Using Python

PDF Text Extraction in Python

How to dissever, relieve, and extract text from PDF files using PyPDF2 and PDFMiner, demonstrated with the consummate works of H. P. Lovecraft.

Mate Pocs

I don't think there is much room for creativity when information technology comes to writing the intro paragraph for a postal service nigh extracting text from a pdf file. There is a pdf, there is text in it, we want the text out, and I am going to show you how to exercise that using Python.

In the starting time part, we are going to have a look at two Python libraries, PyPDF2 and PDFMiner. Equally their proper noun suggests, they are libraries written specifically to piece of work with pdf files. We will talk over the different classes and methods nosotros need.

So , in the 2nd office, we are going to work on one project, which is about splitting a 708-page long pdf file into separate smaller files, extracting the text information, cleaning information technology, and and then exporting to hands readable text files. For more information on this project, please refer to my GitHub repo.

PyPDF2

As a outset pace, install the packet:

          pip install PyPDF2        

The first object we demand is a PdfFileReader:

          reader = PyPDF2.PdfFileReader('Complete_Works_Lovecraft.pdf')        

The parameter is the path to a pdf document we want to work with. You tin get a number of general information most your document with this reader object. For example, reader.documentInfo is an attribute that contains the document data lexicon in this format:

          {'/Writer': 'H.P. Lovecraft',
'/Creator': 'Microsoft® Discussion 2010',
'/CreationDate': "D:20110729214233-04'00'",
'/ModDate': "D:20110729214233-04'00'",
'/Producer': 'Microsoft® Word 2010'}

Yous can also get the total number of pages with reader.numPages.

Perhaps the well-nigh important method is getPage(page_num) which returns one page of the file as a dissever PageObject. Be careful, PageObjects are in a list, so the method uses a goose egg-based alphabetize.

Nosotros are not going to heavily utilise the PageObject form, one extra matter you could consider doing is the extractText method, which converts the contents of a folio to a cord variable. For case, to go the text on the 7th page (call back, nix-index) of a pdf, y'all would outset create a PageObject from the PdfFileReader, and call this method:

          reader.getPage(7-one).extractText()        

Notwithstanding, fifty-fifty the official documentation says this on the method: "This works well for some PDF files, but poorly for others, depending on the generator used." Which is not exactly reassuring, and in my feel, extractText did not work properly, information technology left out first and last lines of pages. This is the principal reason why I also used the other library, PDFMiner, in the project.

Next affair nosotros demand is a PdfFileWriter object. This class has no parameters, you can merely create it like so:

          author = PyPDF2.PdfFileWriter()        

The writer object will keep rail of the pdf file we desire to create. In order to add a page to the file to be created, employ the addPage method, which requires a PageObject object as a parameter. For example, to add a certain page from our input pdf:

          my_page = reader.getPage(7)
writer.addPage(my_page)

And finally, a PdfFileWriter object has a write method that saves the contents in a file. The method requires ane parameter, a file object, which means simply entering the file path won't piece of work. A uncomplicated fashion of creating a file object is by using Python's built-in open up method:

          output_filename = 'pages_we_want_to_save.pdf'          with open(output_filename, 'wb') as output:
writer.write(output)

These are all the classes and methods that we are going to utilise, come across PyPDF2 Documentation for information on additional functionalities.

Now nosotros can read and write pdf files, but at that place is one crucial functionality we notwithstanding need: converting the contents to a text file. For that, we need to utilise a different library, PDFMiner.

PDFMiner

We are going to use pdfminer.6, which is a community-maintained fork of the original PDFMiner library. (The PDFMiner project is no longer maintained equally of 2020.)

First, you need to install it:

          pip install pdfminer.six        

Compared with PyPDF2, PDFMiner's scope is much more limited, it actually focuses only on extracting the text from the source data of a pdf file. The documentation is also very focused, has about iii examples in it, and nosotros will basically use this code that is handily provided in the guide. Since the code seemed to work correctly, I did not experience the demand to dig any deeper.

That's all we should demand for at present, on to our bodily project!

The Lovecraft Projection Introduction

Just to give you some context on why we are doing this project, I want to practice a comprehensive NLP analysis on the works of H. P. Lovecraft. In example you do not know who that is, he was an American writer in the early 20th century, famous for his weird and catholic horror fiction, with a huge influence on modern popular civilisation. If you want a glimpse of his writing style, cheque out this post, and if you desire to read upward on some of the more problematic aspects of his graphic symbol, I recommend this one.

The not bad thing is that his works are officially public domain in the European Matrimony now that lxx years accept passed since his death, and basically public domain in the U.S. considering nobody seems to own the rights. That'due south why everything has Cthulhu in them these days, it'due south free intellectual property. There are multiple sources online where you can gather his works, but interestingly, they are not on Project Gutenberg. I establish another collections that have slight word changes, one example is "frequently" vs. "often" in the start sentence of Across Wall and Sleep, or non containing the quotes, etc.

In the end, I found Arkham Archivist to be a relatively well-documented option (I really liked the name too), downloaded the pdf, and started working on splitting the file and extracting the text.

Putting Theory into Practise

In this section, we are combining what nosotros learned so far. All nosotros need to start is the large pdf file from Arkham Archivist.

There are a couple of general functions nosotros will use, I saved them in a carve up data_func.py file:

Functions:

  • convert_pdf_to_string: that is the generic text extractor code nosotros copied from the pdfminer.6 documentation, and slightly modified then we can utilise information technology as a role;
  • convert_title_to_filename: a function that takes the title as it appears in the table of contents, and converts it to the name of the file- when I started working on this, I assumed we will demand more than adjustments;
  • split_to_title_and_pagenum: the purpose of this office will become clearer later, information technology'southward basically used to decide if a line in the tabular array of contents is really a championship — page number pair, and if yes, returns them in a tuple.

The next step is about setting up the environs, nosotros import the libraries (including the functions from the block above), check some backdrop of the certificate. And most importantly, nosotros set up the PyPDF2 PdfFileReader object we are going to use throughout the project: reader.

At present nosotros can showtime working with the file. Having a look at the pdf, it seems like the all-time course of action is to somehow extract the page numbers from the table of contents, and so use them to split the file. The tabular array of contents is on page iii and 4 in the pdf, which ways 2 and 3 in the PdfFileReader listing of PageObjects. Once we accept the pdf in a separate file, we can employ the pdfminer.six code to excerpt the text information. (Note: we could also just adjust the relevant pages directly without splitting the file, merely I wanted to also create the individual pdf files, and it made sense to accept a separate table of contents file too.)

As of at present, the text variable looks like this:

          'Tabular array of Contents \north\nPreface ............................................................................................................................. 2 \nThe Tomb .......................................................................................................................... five \nDagon ............................................................................................................................. 12            
...

and so on. A couple of simple string replaces:

will convert text to a much nicer format. One needs to exist careful when making adjustments like this, for example, it would besides remove whatsoever '.' that a championship might have, only fortunately, we have no such titles. Nosotros now have a list of the lines in the tabular array of contents:

          ['Table of Contents ',
'',
'Preface 2 ',
'The Tomb 5 ',
'Dagon 12 ',
...

We would like to collect the titles and page numbers into lists. This is washed by stripping abroad the space characters, and then checking if the line ends with numbers. We need to exist careful because nosotros exercise want to keep the spaces inside the titles.

Now that we accept our lists, we can dissever the file into smaller pdfs, saving them in a divide folder:

If we look at the individual pdf files, there are three additional adjustments we would similar to make:

  • Every story has the year information technology was written in brackets later on the title. This is not part of the original text, and we would similar to exclude them. However, we practise want to keep them in a list and then we can use them in futurity assay.
  • Every story has a link dorsum to the table of contents, "Render to Table of Contents", information technology is obviously non part of the original text. I checked and this combination of words (5-gram, every bit nosotros volition come across later in the NLP project) does non appear in any of the original text, so nosotros tin can just delete information technology.
  • The last story has a "Fin" at the end, and a bunch of whitespace. Since the characters "f-i-northward" volition most likely appear in an English language text somewhere, I ended upwardly just cutting the end of the last string.

The code might take a minute to run for all the stories.

Equally a final touch, we salvage the original titles, filenames, page numbers, and year in which it was written in a CSV file.

With that, we are done, we successfully cleaned the text and saved them in separate text files.

Conclusion

I judge the master question is: was it worth doing the project this way? Couldn't I merely find the text files somewhere? As I mentioned, I constitute text sources, but this seemed to be the most reliable. All right, but wouldn't it exist faster to merely copy the text manually? I was thinking about that, but I don't recollect so. Think about all the nuances we applied, gathering the year it was written, deleting the not-core text, etc.

In whatever case, I learned something new, and I promise yous found information technology useful. It was interesting to encounter how many minor problems 1 can run into while working on a relatively unproblematic project like this, and I tin can't await to finally start working on the text. I'1000 really curious nearly how often Lovecraft really used the word "horror" in his writings!

References

DOWNLOAD HERE

Posted by: borrorsopupose.blogspot.com

Post a Comment

Previous Post Next Post

Iklan Banner setelah judul