Unscramble words faster in Python So I'm currently using python to unscramble words that are retrieved from an OCR program (pytesseract).

The current code I am using to unscramble words is this:

import numpy as nm 
import pytesseract 
import cv2 
import ctypes
from PIL import ImageGrab 

def imToString(): 

    # Path of tesseract executable 
    pytesseract.pytesseract.tesseract_cmd =r'C:\Program Files (x86)\Tesseract-OCR\tesseract'
    while(True): 

        # ImageGrab-To capture the screen image in a loop. 
        # Bbox used to capture a specific area. 
        cap = ImageGrab.grab(bbox =(687, 224, 1104, 240))


        # Converted the image to monochrome for it to be easily 
        # read by the OCR and obtained the output String. 
        tesstr = pytesseract.image_to_string( 
                cv2.cvtColor(nm.array(cap), cv2.COLOR_BGR2GRAY), 
                lang ='eng') 
        checkWord(tesstr)

def checkWord(tesstr):

    dictionary =['orange', 'marshmellow']

    scrambled = tesstr
    for word in dictionary:
        if sorted(word) == sorted(scrambled):
            print(word)


imToString() 


I wanna know if there is anyway to reduce the time it takes to:


Scan/Process the image.
Look through the 'dictionary', as there are many more words to go through. Or another more efficient alternative.


Thanks
You are sorting your dictionary each time you use it, do it once and store it.

Also, you are sorting your scrambled word more than once, only do it once:

import numpy as nm 
import pytesseract 
import cv2 
import ctypes
from PIL import ImageGrab 

def imToString(dictionary): 

    # Path of tesseract executable 
    pytesseract.pytesseract.tesseract_cmd =r'C:\Program Files (x86)\Tesseract-OCR\tesseract'
    while(True): 

        # ImageGrab-To capture the screen image in a loop. 
        # Bbox used to capture a specific area. 
        cap = ImageGrab.grab(bbox =(687, 224, 1104, 240))


        # Converted the image to monochrome for it to be easily 
        # read by the OCR and obtained the output String. 
        tesstr = pytesseract.image_to_string( 
                cv2.cvtColor(nm.array(cap), cv2.COLOR_BGR2GRAY), 
                lang ='eng') 
        checkWord(tesstr, dictionary)

def checkWord(tesstr, dictionary):

    scrambled = tesstr
    sorted_scrambled = sorted(scrambled) # Only do this 1 time
    if sorted_scrambled in dictionary:
        print(dictionary[sorted_scrambled]

# ... Create your dictionary somewhere else and pass it in:
dictionary ={sorted('orange'): 'orange',sorted('marshmellow'):  'marshmellow'}

imToString(dictionary)