So extrahieren Sie Text aus PDF in Python

In diesem Tutorial erfahren Sie, wie Sie mithilfe der PyMuPDF-Bibliothek Text aus PDF-Dokumenten in Python extrahieren können .

Beachten Sie, dass dieses Tutorial das Problem behebt, wenn der Text nicht gescannt wird, dh kein Bild in einer PDF-Datei.

Um zu beginnen, müssen wir PyMuPDF installieren:

$ pip install PyMuPDF==1.18.9

Öffnen Sie eine neue Python-Datei und importieren wir die Bibliotheken:
 

import fitz
import argparse
import sys
import os
from pprint import pprint

PyMuPDF hat fitzbeim Importieren in Python den Namen , also denken Sie daran.

Da wir ein Python-Skript erstellen werden, das Text aus PDF-Dokumenten extrahiert, müssen wir das argparse-Modul verwenden, um die übergebenen Parameter in der Befehlszeile zu parsen. Die folgende Funktion parst die Argumente und führt eine Verarbeitung durch:

def get_arguments():
    parser = argparse.ArgumentParser(
        description="A Python script to extract text from PDF documents.")
    parser.add_argument("file", help="Input PDF file")
    parser.add_argument("-p", "--pages", nargs="*", type=int,
                        help="The pages to extract, default is all")
    parser.add_argument("-o", "--output-file", default=sys.stdout,
                        help="Output file to write text. default is standard output")
    parser.add_argument("-b", "--by-page", action="store_true",
                        help="Whether to output text by page. If not specified, all text is joined and will be written together")
    # parse the arguments from the command-line
    args = parser.parse_args()

    input_file = args.file
    pages = args.pages
    by_page = args.by_page
    output_file = args.output_file
    # print the arguments, just for logging purposes
    pprint(vars(args))
    # load the pdf file
    pdf = fitz.open(input_file)
    if not pages:
        # if pages is not set, default is all pages of the input PDF document
        pages = list(range(pdf.pageCount))
    # we make our dictionary that maps each pdf page to its corresponding file
    # based on passed arguments
    if by_page:
        if output_file is not sys.stdout:
            # if by_page and output_file are set, open all those files
            file_name, ext = os.path.splitext(output_file)
            output_files = { pn: open(f"{file_name}-{pn}{ext}", "w") for pn in pages }
        else:
            # if output file is standard output, do not open
            output_files = { pn: output_file for pn in pages }
    else:
        if output_file is not sys.stdout:
            # a single file, open it
            output_file = open(output_file, "w")
            output_files = { pn: output_file for pn in pages }
        else:
            # if output file is standard output, do not open
            output_files = { pn: output_file for pn in pages }

    # return the parsed and processed arguments
    return {
        "pdf": pdf,
        "output_files": output_files,
        "pages": pages,
    }

Zuerst haben wir unseren Parser mit erstellt ArgumentParserund die folgenden Parameter hinzugefügt:

  • file: Das Eingabe-PDF-Dokument, aus dem Text extrahiert werden soll.
  • -poder --pages: Die zu extrahierenden Seitenindizes, beginnend bei 0, wenn Sie nichts angeben, werden standardmäßig alle Seiten verwendet.
  • -ooder --output-file: Die Ausgabetextdatei, um den extrahierten Text zu schreiben. Wenn Sie nichts angeben, wird der Inhalt in der Standardausgabe (dh in der Konsole) ausgegeben.
  • -boder --by-page: Dies ist ein boolescher Wert, der angibt, ob Text seitenweise ausgegeben werden soll. Wenn nicht angegeben, wird der gesamte Text in einer einzigen Datei zusammengeführt (wenn -oangegeben).

Zweitens öffnen wir unsere output_fileszum Einschreiben, wenn -bangegeben ist. Andernfalls befindet sich eine einzelne Datei im output_filesWörterbuch.

Schließlich geben wir die erforderlichen Variablen zurück: PDF-Dokument, Ausgabedateien und die Liste der Seitenzahlen.

Als Nächstes erstellen wir eine Funktion, die die obigen Parameter akzeptiert und entsprechend Text aus PDF-Dokumenten extrahiert:

def extract_text(**kwargs):
    # extract the arguments
    pdf          = kwargs.get("pdf")
    output_files = kwargs.get("output_files")
    pages        = kwargs.get("pages")
    # iterate over pages
    for pg in range(pdf.pageCount):
        if pg in pages:
            # get the page object
            page = pdf[pg]
            # extract the text of that page and split by new lines '\n'
            page_lines = page.get_text().splitlines()
            # get the output file
            file = output_files[pg]
            # get the number of lines
            n_lines = len(page_lines)
            for line in page_lines:
                # remove any whitespaces in the end & beginning of the line
                line = line.strip()
                # print the line to the file/stdout
                print(line, file=file)
            print(f"[*] Wrote {n_lines} lines in page {pg}")    
    # close the files
    for pn, f in output_files.items():
        if f is not sys.stdout:
            f.close()

Wir durchlaufen die Seiten. Wenn die Seite, auf der wir uns befinden, in der pagesListe enthalten ist, extrahieren wir den Text dieser Seite und schreiben ihn in die angegebene Datei oder Standardausgabe. Schließlich schließen wir die Dateien.

Lassen Sie uns alles zusammenbringen und die Funktionen ausführen:

if __name__ == "__main__":
    # get the arguments
    kwargs = get_arguments()
    # extract text from the pdf document
    extract_text(**kwargs)

Großartig, versuchen wir, den Text aus allen Seiten dieser Datei zu extrahieren und jede Seite in eine Textdatei zu schreiben:

$ python extract_text_from_pdf.py bert-paper.pdf -o text.txt -b

Ausgabe:

{'by_page': True,
 'file': 'bert-paper.pdf', 
 'output_file': 'text.txt',
 'pages': None}
[*] Wrote 97 lines in page 0
[*] Wrote 108 lines in page 1
[*] Wrote 136 lines in page 2
[*] Wrote 107 lines in page 3
[*] Wrote 133 lines in page 4
[*] Wrote 158 lines in page 5
[*] Wrote 163 lines in page 6
[*] Wrote 128 lines in page 7
[*] Wrote 158 lines in page 8
[*] Wrote 116 lines in page 9
[*] Wrote 124 lines in page 10
[*] Wrote 115 lines in page 11
[*] Wrote 135 lines in page 12
[*] Wrote 111 lines in page 13
[*] Wrote 153 lines in page 14
[*] Wrote 127 lines in page 15

Hat einwandfrei funktioniert, hier die Ausgabedateien:

Geben wir nun die Seiten 0, 1, 2, 14 und 15 an:

$ python extract_text_from_pdf.py bert-paper.pdf -o text.txt -b -p 0 1 2 14 15   
{'by_page': True,
 'file': 'bert-paper.pdf',
 'output_file': 'text.txt',
 'pages': [0, 1, 2, 14, 15]}
[*] Wrote 97 lines in page 0
[*] Wrote 108 lines in page 1
[*] Wrote 136 lines in page 2
[*] Wrote 153 lines in page 14
[*] Wrote 127 lines in page 15

Wir können auch in der Konsole drucken, anstatt es in einer Datei zu speichern, indem wir die -oOption nicht angeben :

$ python extract_text_from_pdf.py bert-paper.pdf -p 0
{'by_page': False,
 'file': 'bert-paper.pdf',
 'output_file': <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>,
 'pages': [0]}
BERT: Pre-training of Deep Bidirectional Transformers for
Language Understanding
Jacob Devlin
Ming-Wei Chang
Kenton Lee
Kristina Toutanova
Google AI Language
{jacobdevlin,mingweichang,kentonl,kristout}@google.com
Abstract
We introduce a new language representa-
tion model called BERT, which stands for
Bidirectional Encoder Representations from
...
<SNIPPED>
[*] Wrote 97 lines in page 0

Oder speichern Sie den gesamten Text des PDF-Dokuments in einer einzigen Textdatei:

$ python extract_text_from_pdf.py bert-paper.pdf -o all-text.txt

Die Ausgabedatei wird im aktuellen Verzeichnis angezeigt:

Okay, das war's für dieses Tutorial. Wie bereits erwähnt,

What is GEEK

Buddha Community

Shardul Bhatt

Shardul Bhatt

1626775355

Why use Python for Software Development

No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas. 

By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities. 

Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly. 

5 Reasons to Utilize Python for Programming Web Apps 

Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.

Robust frameworks 

Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions. 

Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events. 

Simple to read and compose 

Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building. 

The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties. 

Utilized by the best 

Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player. 

Massive community support 

Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions. 

Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking. 

Progressive applications 

Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.

The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.

Summary

Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential. 

The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.

#python development services #python development company #python app development #python development #python in web development #python software development

August  Larson

August Larson

1624428000

Creating PDF Invoices in Python with pText

Introduction

The Portable Document Format (PDF) is not a WYSIWYG (What You See is What You Get) format. It was developed to be platform-agnostic, independent of the underlying operating system and rendering engines.

To achieve this, PDF was constructed to be interacted with via something more like a programming language, and relies on a series of instructions and operations to achieve a result. In fact, PDF is based on a scripting language - PostScript, which was the first device-independent Page Description Language.

In this guide, we’ll be using pText - a Python library dedicated to reading, manipulating and generating PDF documents. It offers both a low-level model (allowing you access to the exact coordinates and layout if you choose to use those) and a high-level model (where you can delegate the precise calculations of margins, positions, etc to a layout manager).

We’ll take a look at how to create a PDF invoice in Python using pText.

#python #pdf #creating pdf invoices in python with ptext #creating pdf invoices #pdf invoice #creating pdf invoices in python with ptext

Navigating Between DOM Nodes in JavaScript

In the previous chapters you've learnt how to select individual elements on a web page. But there are many occasions where you need to access a child, parent or ancestor element. See the JavaScript DOM nodes chapter to understand the logical relationships between the nodes in a DOM tree.

DOM node provides several properties and methods that allow you to navigate or traverse through the tree structure of the DOM and make changes very easily. In the following section we will learn how to navigate up, down, and sideways in the DOM tree using JavaScript.

Accessing the Child Nodes

You can use the firstChild and lastChild properties of the DOM node to access the first and last direct child node of a node, respectively. If the node doesn't have any child element, it returns null.

Example

<div id="main">
    <h1 id="title">My Heading</h1>
    <p id="hint"><span>This is some text.</span></p>
</div>

<script>
var main = document.getElementById("main");
console.log(main.firstChild.nodeName); // Prints: #text

var hint = document.getElementById("hint");
console.log(hint.firstChild.nodeName); // Prints: SPAN
</script>

Note: The nodeName is a read-only property that returns the name of the current node as a string. For example, it returns the tag name for element node, #text for text node, #comment for comment node, #document for document node, and so on.

If you notice the above example, the nodeName of the first-child node of the main DIV element returns #text instead of H1. Because, whitespace such as spaces, tabs, newlines, etc. are valid characters and they form #text nodes and become a part of the DOM tree. Therefore, since the <div> tag contains a newline before the <h1> tag, so it will create a #text node.

To avoid the issue with firstChild and lastChild returning #text or #comment nodes, you could alternatively use the firstElementChild and lastElementChild properties to return only the first and last element node, respectively. But, it will not work in IE 9 and earlier.

Example

<div id="main">
    <h1 id="title">My Heading</h1>
    <p id="hint"><span>This is some text.</span></p>
</div>

<script>
var main = document.getElementById("main");
alert(main.firstElementChild.nodeName); // Outputs: H1
main.firstElementChild.style.color = "red";

var hint = document.getElementById("hint");
alert(hint.firstElementChild.nodeName); // Outputs: SPAN
hint.firstElementChild.style.color = "blue";
</script>

Similarly, you can use the childNodes property to access all child nodes of a given element, where the first child node is assigned index 0. Here's an example:

Example

<div id="main">
    <h1 id="title">My Heading</h1>
    <p id="hint"><span>This is some text.</span></p>
</div>

<script>
var main = document.getElementById("main");

// First check that the element has child nodes 
if(main.hasChildNodes()) {
    var nodes = main.childNodes;
    
    // Loop through node list and display node name
    for(var i = 0; i < nodes.length; i++) {
        alert(nodes[i].nodeName);
    }
}
</script>

The childNodes returns all child nodes, including non-element nodes like text and comment nodes. To get a collection of only elements, use children property instead.

Example

<div id="main">
    <h1 id="title">My Heading</h1>
    <p id="hint"><span>This is some text.</span></p>
</div>

<script>
var main = document.getElementById("main");

// First check that the element has child nodes 
if(main.hasChildNodes()) {
    var nodes = main.children;
    
    // Loop through node list and display node name
    for(var i = 0; i < nodes.length; i++) {
        alert(nodes[i].nodeName);
    }
}
</script>

#javascript 

Alec  Nikolaus

Alec Nikolaus

1599758100

Convert Text to Speech in Python

Learn how to convert your Text into Voice with Python and Google APIs

Text to speech is a process to convert any text into voice. Text to speech project takes words on digital devices and convert them into audio with a button click or finger touch. Text to speech python project is very helpful for people who are struggling with reading.

Project Prerequisites

To implement this project, we will use the basic concepts of Python, Tkinter, gTTS, and playsound libraries.

  • Tkinter is a standard GUI Python library that is one of the fastest and easiest ways to build GUI applications using Tkinter.
  • gTTS (Google Text-to-Speech) is a Python library, which is a very easy library that converts the text into audio.
  • The playsound module is used to play audio files. With this module, we can play a sound file with a single line of code.

To install the required libraries, you can use pip install command:

pip install tkinter
pip install gTTS
pip install playsound

Download Python Text to Speech Project Code

Please download the source code of Text to Speech Project: Python Text to Speech

Text to Speech Python Project

The objective of this project is to convert the text into voice with the click of a button. This project will be developed using Tkinter, gTTs, and playsound library.

In this project, we add a message which we want to convert into voice and click on play button to play the voice of that text message.

  • Importing the modules
  • Create the display window
  • Define functions

So these are the basic steps that we will do in this Python project. Let’s start.

#python tutorials #python project #python project for beginners #python text to speech #text to speech convertor #python

Art  Lind

Art Lind

1602968400

Python Tricks Every Developer Should Know

Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?

In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.

Let’s get started

Swapping value in Python

Instead of creating a temporary variable to hold the value of the one while swapping, you can do this instead

>>> FirstName = "kalebu"
>>> LastName = "Jordan"
>>> FirstName, LastName = LastName, FirstName 
>>> print(FirstName, LastName)
('Jordan', 'kalebu')

#python #python-programming #python3 #python-tutorials #learn-python #python-tips #python-skills #python-development