Search Documents for a Phrase - Python

This tutorial shows how to search documents for a phrase in a Python application using the LEADTOOLS SDK.

Overview  
Summary This tutorial covers how to search for a phrase in a Python application.
Completion Time 10 minutes
Visual Studio Project Download tutorial project (2 KB)
Platform Python Console Application
IDE Visual Studio 2022
Runtime Target Python 3.10 or Higher
Development License Download LEADTOOLS
Try it in another language

Required Knowledge

Get familiar with the basic steps of creating a project by reviewing the Add References and Set a License tutorial, before working on the Search Documents for a Phrase - Python tutorial.

Create the Project and Add LEADTOOLS References

Start with a copy of the project created in the Add References and Set a License tutorial. If you do not have that project, follow the steps in that tutorial to create it.

The references needed depend upon the purpose of the project.

This tutorial requires the following .NET DLLs:

For a complete list of which DLL files are required for your application, refer to Files to be Included With Your Application.

Set the License File

The License unlocks the features needed for the project. It must be set before any toolkit function is called. For details, including tutorials for different platforms, refer to Setting a Runtime License.

There are two types of runtime licenses:

Add the Search for a Phrase Code

With the project created, the references added, and the license set, coding can begin.

In the Solution Explorer, open Project-Name.py and place the following references below the "Add references to LEADTOOLS" comment

# Add references to LEADTOOLS 
from leadtools import LibraryLoader 
LibraryLoader.add_reference("Leadtools") 
from Leadtools import * 
LibraryLoader.add_reference("Leadtools.Ocr") 
from Leadtools.Ocr import * 
LibraryLoader.add_reference("Leadtools.Document") 
from Leadtools.Document import * 
 
from System.Text.RegularExpressions import * 
from System.Collections.Generic import * 

In the main() method add the following code:

def main(): 
 
    Support.set_license(os.path.join(DemosTools.get_root(), "C:/LEADTOOLS23/Support/Common/License")) 
 
    search_string = "LEAD Technologies"  
    file = r"C:\LEADTOOLS23\LICENSE.pdf" 
 
    options = LoadDocumentOptions() 
    options.useCache = True 
    document = DocumentFactory.LoadFromFile(file, options) 
    find_phrase(search_string, document) 

Note: You can modify the variables search_string and file to use different files or phrases with this application.

Add a new function to the Project-Name.py file named find_phrase(search_string, document). This method will be called inside the main() method, as shown above. Add the code below to find the number of times the given phrase is in the document.

def find_phrase(search_string, document): 
 
    ocr_engine = OcrEngineManager.CreateEngine(OcrEngineType.LEAD) 
    ocr_engine.Startup(None, None, None, "C:\LEADTOOLS23\Bin\Common\OcrLEADRuntime") 
 
    document.Text.OcrEngine = ocr_engine 
 
    for page in document.Pages: 
        text = page.GetText() 
        text.BuildTextWithMap() 
        text.BuildWords() 
 
        regex = Regex(fr"\b({search_string})\b", RegexOptions.IgnoreCase | RegexOptions.Multiline) 
        matches = regex.Matches(text.Text) 
         
        for match in matches: 
            first_capture = match.Captures[0] 
            words = List[DocumentWord]() 
            first_char_index = first_capture.Index 
            length = first_capture.Length 
 
            for index in range(first_char_index, first_char_index + length): 
                char_index = text.TextMap[index] 
                if (char_index > 0): 
                    character = text.Characters[char_index] 
                    if (character.IsEndOfWord): 
                        word = next(word for word in text.Words if word.LastCharacterIndex == char_index) 
                        if (word != None): 
                            words.Add(word) 
            # Combine the word bounds to get the phrase bounds 
            phrase_rect = [word.Bounds for word in words] 
            for i in range(1, words.Count): 
                phrase_rect = words[i].Bounds 
                phrase_rect.Union(words[i].Bounds) 
 
            pixel_bounds = document.RectToPixels(phrase_rect[0]) 
            print(f"{search_string} found on page {page.PageNumber} at {pixel_bounds}") 

Note: The above code snippet will print to the console for every matched phrase detected in the LEADDocument. It returns the page number of the page and the location on the page where the phrase can be found. The location returned is in terms of pixels on the page. If you want the coordinates to be compatible to altering a document in a viewer, you must use the RectToContainerCoordinates method.

Run the Project

Run the project by pressing F5, or by selecting Debug -> Start Debugging.

If the steps were followed correctly, the console appears and the application will search the chosen document for the chosen phrase.

Phrase Search Console Output

Wrap-up

This tutorial showed how to use the LEADTOOLS SDK to load a file, search for a phrase, and return the location of every instance of the phrase.

See Also

Help Version 23.0.2024.5.22
Products | Support | Contact Us | Intellectual Property Notices
© 1991-2024 LEAD Technologies, Inc. All Rights Reserved.

Products | Support | Contact Us | Intellectual Property Notices
© 1991-2023 LEAD Technologies, Inc. All Rights Reserved.