Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- from sys import argv, stderr
- from os import system as cmd
- from math import floor
- from os.path import exists
- from pprint import pprint
- from random import choices, randint
- def errFatal(errorString, returnCode = -1):
- print('ERROR: '+errorString, file=stderr)
- exit(returnCode)
- def rnd(x): return floor(x+0.5) # Python's built-in rounding is stupid
- def toInt(x):
- try: return rnd(eval(x))
- except Exception: return None
- wordCount = toInt(argv[1]) if len(argv) > 1 else 50
- fileIn_name = argv[2] if len(argv) > 2 else 'input.txt'
- word = argv[3].lower() if len(argv) > 3 else None
- if wordCount is None:
- errFatal('Word count provided is not an integer value')
- if not exists(fileIn_name):
- errFatal(f'File "{fileIn_name}" doesn\'t exist!')
- def strip_all(s):
- return s.strip(" \"'!?.,;:").lower()
- def split_all(s):
- # Split by line breaks and spaces
- l_0 = ( (' ').join(s.splitlines()) ).split(' ')
- # Split by dashes
- l_1 = ( ('-').join(l_0) ).split('-')
- # Strip each string in list, while culling empty strings
- return [strip_all(_s) for _s in l_1 if _s != '']
- def convert_word_dict(d):
- next_words = []
- weights = []
- for k in d:
- next_words.append(k)
- weights.append(d[k])
- return [next_words, weights]
- def build_dictionary(l):
- if len(l) <= 1: return None
- dict_a = {}
- for i in range(len(l)-1):
- current = l[i ]
- next = l[i+1]
- if not current in dict_a:
- dict_a[current] = {}
- if not next in dict_a[current]:
- dict_a[current][next] = 0
- dict_a[current][next] += 1
- dict_b = {}
- for word in dict_a:
- dict_b[word] = convert_word_dict(dict_a[word])
- return dict_b
- def get_next_word(word, dictionary):
- if not word in dictionary: return None
- words_and_weights = dictionary[word]
- return choices(words_and_weights[0],
- words_and_weights[1], k=1)[0]
- if __name__ == '__main__':
- file = open(fileIn_name, 'r')
- data = split_all(file.read())
- file.close()
- dict = build_dictionary(data)
- if word is None:
- word = data[ randint(0,len(data)-1) ]
- if get_next_word(word, dict) is None:
- errFatal(f'"{word}" does not have an entry in the word dictionary!')
- for i in range(wordCount):
- print(word, end=' ')
- word = get_next_word(word, dict)
- if word is None: word = data[ randint(0,len(data)-1) ]
- '''
- 'youth': {'and': 1,
- 'heroes': 1,
- 'inclined': 1,
- 'into': 1,
- 'of': 1,
- 'was': 2,
- 'who': 1,
- 'with': 1},
- '''
Advertisement
Add Comment
Please, Sign In to add comment