from utilities import readfile, printtable from NgramAutocomplete import…
- User
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) # print_table(tables, 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()
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))Help me make 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. """ - Assistant
- User
What about this?
frequency_tables = []
code# Loop through each level of n-gram (from 1 to n) for i in range(1, n + 1): # Initialize a frequency table for the i-th n-gram (e.g., unigram, bigram, etc.) freq_table = defaultdict(int) # Loop through the document to populate the frequency table for j in range(len(document) - i + 1): # Extract the i-length n-gram from the document ngram = document[j:j + i] # Increment the frequency of the current n-gram in the frequency table freq_table[ngram] += 1 # Append the completed frequency table for this level of n-gram frequency_tables.append(dict(freq_table)) # Convert to dict for better readability print(frequency_tables) return frequency_tables - Assistant
- User
which should i do
- Assistant