0

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
  • 4
    I am not clear where recursion comes into place... – sal Dec 12 '19 at 00:54
  • Recursion is when a function calls itself in its body, with some exit condition that allows recursion to end and provide a result (rather than looping until an exception is raised). Please check if your program generates the intermediate output that you expect: maybe the issue starts somewhere else. For one example of recursion, you can look here: https://stackoverflow.com/questions/13708670/recursion-function-in-python – sal Dec 12 '19 at 01:14
  • 1
    Also, do yourself (and everyone here) a favour and use a consistent indent depth in your code - 4 spaces is standard. You have 4, 2 and 1 mixed in there and it's almost certainly going to lead to hard to find errors. – Grismar Dec 12 '19 at 01:14
  • Got it. Uh..Thanks I guess. – Geni Allaine Dec 12 '19 at 03:00

0 Answers0