This is my bigrams program. I enter a text file "Passage.txt" and the program takes the excerpt and makes a dictionary. The objective is to choose a key from the dictionary, print it and then look at its values. Its values will have names that match other keys in the dictionary, so a value is chosen at random and the process repeats on the corresponding key until you reach the input number of words. I am able to print the first key and a random value from the key. I am not able to take the random value, find the dictionary key with the matching name of the value and repeat the process.
import random
def getwords(file_name):
with open(file_name, 'r') as file:
text = file.read().lower()
stop_letters = (".", ",", ";", ":", "'s", '"', "!", "?", "(", ")", '“', '”')
text = ''.join([letter if letter not in stop_letters else '' for letter in text])
words = text.split()
return words
def compute_bigrams(fileName):
input_list = getwords(fileName)
bigram_list = {}
for i in range(len(input_list) - 1):
if input_list[i] in bigram_list:
bigram_list[input_list[i]] = bigram_list[input_list[i]] + [input_list[i + 1]]
else :
bigram_list[input_list[i]] = [input_list[i + 1]]
return bigram_list
wordReturn = int(input("How many words is your output?: "))
accessKey = int(input("Choose a key: "))
#Return key name from input and corresponding list
def generateBigramsText(fileName):
bigrams = compute_bigrams(fileName)
key = list(bigrams.keys())[accessKey]
bigramWord = bigrams[list(bigrams.keys())[accessKey]]
return key , bigramWord
#Use Tuple to print key and random word from BigramWord list
def generateRandomText(fileName):
bigram2 = generateBigramsText(fileName)
thisKey = bigram2[0]
newList = list(bigram2[1])
nextWord = random.choice(newList)
for x in range(wordReturn):
thisKey = nextWord
return thisKey