Fun With Dictionaries 😁¶

Group words by first and last letter¶

first_and_last.py¶

In [ ]:
groups = {}

response = input('Word: ')
while response:
    
    key = (response[0], response[-1])
    
    if key not in groups:
        groups[key] = []
    
    groups[key].append(response)

    response = input('Word: ')
    
print(groups)

I Nephi...¶

Given the text of 1 Nephi, group words by preceding word.

Then use the result to randomly generate text.

nephi.py¶

In [ ]:
def group_by_previous(words):
    prev = None
    groups = {}
    for word in words:
        word = word.strip('.,;!?')
        
        if prev is None:
            prev = word
            continue
        
        key = prev.lower()
        if key not in groups:
            groups[key] = []
        
        groups[key].append(word)
        
        prev = word
    return groups
In [ ]:
groups = group_by_previous("""
And it came to pass that I Nephi said unto my father 
I will go and do the things which the Lord has commanded
for I know that the Lord giveth no commandments unto the 
children of men save He shall prepare a way that they may
accomplish the things that He commandeth them
""".split())
groups
In [ ]:
import random

word = 'and'
words = [word]

for _ in range(20):
    word = random.choice(groups[word.lower()])
    words.append(word)

print(" ".join(words))
In [ ]: