Guest User

Untitled

a guest
Apr 10th, 2017
567
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. """Implements and prints out a markov chain"""
  2.  
  3. import random
  4.  
  5. def main():
  6. file1 = input("Enter file name >>> ")
  7. firstWords = []
  8. dict1 = {} #A dictionary storing each word and a list of all words that can follow it
  9. flag = 1
  10. count = 0
  11.  
  12. #Open the file named file1 in reading mode, and call the open file descriptor f1
  13. with open(file1, "r") as f1:
  14. #Loop through the open file line by line
  15. for line in f1:
  16. #Split each line into a list
  17. tempList = line.split()
  18.  
  19. #If that line wasn't empty, add its first word to the list of first words
  20. if len(tempList) > 0:
  21. firstWords.append(tempList[0])
  22.  
  23. #Walk through the entire line
  24. for i in range(0, len(tempList)):
  25. #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
  26. if tempList[i] not in dict1:
  27. dict1[tempList[i]] = []
  28. #otherwise, so long as it isn't punctuation, add the next word to the list of that dictionary entry
  29. if tempList[i] != '.' and tempList[i] != ',' and i < len(tempList) - 1:
  30. dict1[tempList[i]].append(tempList[i + 1])
  31.  
  32. #Choose any word from the file that was the start of a sentance
  33. string = random.choice(firstWords)
  34.  
  35. #While the current word as a non-empty list as its value (basically, there's some word that can follow it) keep looping
  36. #And for simplicity, just stop if we hit 100 in a chain. No need to go forever.
  37. while flag == 1 and count < 100:
  38. count = count + 1
  39. print(string, end=' ')
  40.  
  41. #Change from the current string into one of the possible words that could follow it, and continue with the loop
  42. if len(dict1[string]) != 0:
  43. string = random.choice(dict1[string])
  44. #The current word doesn't have anything that can follow it. So we're at the end of the chain.
  45. elif len(dict1[string]) == 0:
  46. flag = 0
  47. #Put a newline after the chain is done for pretty-print reasons
  48. print('')
  49.  
  50. if __name__ == "__main__":
  51. main()
Add Comment
Please, Sign In to add comment