s = "One night--it was on the twentieth of March, 1888--I was returning from a journey to a patient (for I had now returned to civil practice), when my way led me through Baker Street. As I passed the well-remembered door, which must always be associated in my mind with my wooing, and with the dark incidents of the Study in Scarlet, I was seized with a keen desire to see Holmes again, and to know how he was employing his extraordinary powers. His rooms were brilliantly lit, and, even as I looked up, I saw his tall, spare figure pass twice in a dark silhouette against the blind. He was pacing the room swiftly, eagerly, with his head sunk upon his chest and his hands clasped behind him. To me, who knew his every mood and habit, his attitude and manner told their own story. He was at work again. He had risen out of his drug-created dreams and was hot upon the scent of some new problem. I rang the bell and was shown up to the chamber which had formerly been in part my own."

import re
import random 

regx = re.compile("(\w[\w']*\w|\w)")

def produce_trigram(s):
    words = regx.findall(s)
    
    if len(s) <= 2:
        return None
    
    trigram = dict()
    for i in range(len(words)-2):
        key = words[i] + " " + words[i+1]
        value = words[i+2]
        
        if not trigram.get(key):
            trigram[key] = [value]
        else:
            trigram[key].append(value)
        
    return trigram

def write_story(trigram):
    new_string = key = random.choice(list(trigram.keys()))
    
    while trigram:
        value_list = trigram.get(key)

        if not value_list:
            key = random.choice(list(trigram.keys()))
        else:
            value = value_list.pop(0)
            
            if not value_list:
                trigram.pop(key, None)
                
            new_string = new_string + " " + value
            
            key = new_string.split()
            key = key[-2] + " " + key[-1]
    
    return new_string
    
print(write_story(produce_trigram(s)))