Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """Implements and prints out a markov chain"""
- import random
- def main():
- file1 = input("Enter file name >>> ")
- firstWords = []
- dict1 = {} #A dictionary storing each word and a list of all words that can follow it
- flag = 1
- count = 0
- #Open the file named file1 in reading mode, and call the open file descriptor f1
- with open(file1, "r") as f1:
- #Loop through the open file line by line
- for line in f1:
- #Split each line into a list
- tempList = line.split()
- #If that line wasn't empty, add its first word to the list of first words
- if len(tempList) > 0:
- firstWords.append(tempList[0])
- #Walk through the entire line
- for i in range(0, len(tempList)):
- #if the word in the line isn't in the dictionary, add it to the dictionary and give its value to be a new list
- if tempList[i] not in dict1:
- dict1[tempList[i]] = []
- #otherwise, so long as it isn't punctuation, add the next word to the list of that dictionary entry
- if tempList[i] != '.' and tempList[i] != ',' and i < len(tempList) - 1:
- dict1[tempList[i]].append(tempList[i + 1])
- #Choose any word from the file that was the start of a sentance
- string = random.choice(firstWords)
- #While the current word as a non-empty list as its value (basically, there's some word that can follow it) keep looping
- #And for simplicity, just stop if we hit 100 in a chain. No need to go forever.
- while flag == 1 and count < 100:
- count = count + 1
- print(string, end=' ')
- #Change from the current string into one of the possible words that could follow it, and continue with the loop
- if len(dict1[string]) != 0:
- string = random.choice(dict1[string])
- #The current word doesn't have anything that can follow it. So we're at the end of the chain.
- elif len(dict1[string]) == 0:
- flag = 0
- #Put a newline after the chain is done for pretty-print reasons
- print('')
- if __name__ == "__main__":
- main()
Add Comment
Please, Sign In to add comment