Mar-17-2019, 12:07 AM
#! python3 # using the inauguration speech of William Henry Harrison analyzed in the previous example, we can write the following code that generates arbitrarily # long Markov chains (with the chain length set to 100) based on the #structure of its text import requests from random import randint def wordListSum(wordList): sum = 0 for word, value in wordList.items(): sum += value return sum def retrieveRandomWord(wordList): randIndex = randint(1, wordListSum(wordList)) for word, value in wordList.items(): randIndex -= value if randIndex <= 0: return word def buildWordDict(text): # Remove newlines and quotes text = text.replace("\n", " ") text = text.replace('"', "") # Make sure punctuation marks are treated as their own "words" # so that they will be included in the Markov chain punctuation = [",", ".", ";", ":"] for symbol in punctuation: text = text.replace(symbol, " " + symbol + " ") words = text.split(" ") # Filter out empty words words = [word for word in words if word != ""] wordDict = {} for i in range(1, len(words)): if words[i - 1] not in wordDict: # Create a new dictionary for this word wordDict[words[i - 1]] = {} if words[i] not in wordDict[words[i - 1]]: wordDict[words[i - 1]][words[i]] = 0 wordDict[words[i - 1]][words[i]] += 1 return wordDict text = requests.get("http://pythonscraping.com/files/inaugurationSpeech.txt") if text.status_code == 200: content = text.text wordDict = buildWordDict(text) # Generate a Markov chain of length 100 length = 100 chain = "" currentWord = "I" for i in range(0, length): chain += currentWord + " " currentWord = retrieveRandomWord(wordDict[currentWord]) print(chain)
Error:Traceback (most recent call last):
File "C:\Python36\kodovi\markov.py", line 49, in <module>
wordDict = buildWordDict(text)
File "C:\Python36\kodovi\markov.py", line 25, in buildWordDict
text = text.replace("\n", " ")
AttributeError: 'Response' object has no attribute 'replace'
>>>
There is a replace method in the documentation, does this message means that there is not attribute new line?And what is wrong with the line 49?