here's how my main.py works: from utilities import readfile, printtable from…
- User
here's how my main.py works: from utilities import read_file, print_table from NgramAutocomplete import create_frequency_tables, calculate_probability, predict_next_char
def main(): document = read_file('warandpeace.txt') n = int(input("Enter the number of grams (n): ")) initial_sequence = input(f"Enter an initial sequence: ") k = int(input("Enter the length of completion (k): "))
codetables = create_frequency_tables(document, n) vocabulary = set(tables[0]) current_sequence = initial_sequence for _ in range(k): # Predict the most likely next character next_char = predict_next_char(current_sequence[-n:], tables, vocabulary) current_sequence += next_char print(f"Updated sequence: {current_sequence}")if name == "main": main()
and here's my NgramAutocomplete.py: from collections import defaultdict
def create_frequency_tables(document, n): """ This function constructs a list of
nfrequency tables for an n-gram model, each table capturing character frequencies with increasing conditional dependencies.code- **Parameters**: - `document`: The text document used to train the model. - `n`: The number of value of `n` for the n-gram model. - **Returns**: - Returns a list of n frequency tables. """ frequency_tables = [defaultdict(lambda: defaultdict(int)) for _ in range(n)] for i in range(len(document)): current = document[i] for length in range(n): if i - length -1 >= 0: context = document[i-length-1:i] frequency_tables[length][current][context] += 1 return frequency_tablesdef calculate_probability(sequence, char, tables): """ Calculates the probability of observing a given sequence of characters using the frequency tables.
code - Assistant
- User
i made the changes that you recommended: Enter the number of grams (n): 3 Enter an initial sequence: aa Enter the length of completion (k): 4 Updated sequence: aa
Updated sequence: aa
Updated sequence: aa
Updated sequence: aa
- Assistant
- User
these are my utilities function for reference: from collections import defaultdict
def read_file(filename): with open(filename, "r", encoding="utf-8") as file: text = file.read().lower() return text
Print the frequency tables
def print_table(tables, n): n += 1 for i in range(n): print(f"Table {i+1} (n(i_{i+1} | i_{i}, ..., i_1)):") for char, prev_chars_dict in tables[i].items(): for prev_chars, count in prev_chars_dict.items(): print(f" P({char} | {prev_chars}) = {count}")
codek = 0 for i in tables: print(f"Printing table {k}") k += 1 for j, v in i.items(): print(j, ' : ', dict(v)) - Assistant