import csv
import json

with open('BY HAND rick_only_nb.csv', newline='', encoding='utf-8') as csvfile:
    csv_data = csv.reader(csvfile, delimiter=',', quotechar='"') #read the csv data with the correct format
    data = [] 
    for row in csv_data:
        data.append(row) #then turn the csv data into a list

Rick_lines = []
for line in data:
    Rick_lines.append(line[3])

for i in range(len(Rick_lines)):
    Rick_lines[i] = Rick_lines[i].split()
Rick_lines[:10]

def generate_MMn(n):
    if n < 1:
        return 'error'
    
    MMn_build = {}
    
    for line in Rick_lines:
        key = ['']*(n-1)
        key += ['START']

        for word in line:
            if word != '*burps*':
                used_key = " ".join(key)
                if used_key not in MMn_build:
                    MMn_build[used_key] = {}
                if word in MMn_build[used_key]:
                    MMn_build[used_key][word] += 1
                else:
                    MMn_build[used_key][word] = 1
                key.append(word)
                key.pop(0)
        # Then we add the dumb state 'STOP'
        used_key = " ".join(key)
        if used_key not in MMn_build:
            MMn_build[used_key] = {}
        if 'STOP' in MMn_build[used_key]:
            MMn_build[used_key]['STOP'] += 1
        else:
            MMn_build[used_key]['STOP'] = 1
    
    for key in MMn_build:
        MMn_build[key] = [list(MMn_build[key].keys()), list(MMn_build[key].values())]
    
    with open("data_MM"+str(n)+".json", "w") as write_file:
        json.dump(MMn_build, write_file)