Which algorithm is suitable to find occurrence of words in text file

For each sentence, for each pair of words <w1,w2> of the sentence, compute the distance (i.e. the number of words between w1 and w2 in the sentence). For instance considering the pair <”this", “example”>, we have two occurrences in s1, 1 occurrence in s2 and 1 occurrence in s3. In s1 distances are 3 and 6, in s2 3 and in s3 1. Finally, the average distance for the pair <”this”, "example”> is 3.25 All pairs, with relative average distance must be written in a table of a relational database

how to solve this problem in python.

which algorithm or methods or function is best solution for this problem ? if there any suitable code please share here.

Thanks