I am trying to use code to develop a Markov chain that will create random sentences from a string. I have already split the string and am evaluating it. My current code is:
#Your code here
string = '''how much wood could a woodchuck chuck
if a woodchuck could chuck wood?
as much wood as a woodchuck could chuck
if a woodchuck could chuck wood.'''
st_dict={}
for i in range(0, len(words)-1):
#print(words)
word=words[i]
next_word=words[i+1]
if word in ['.','?']:
st_dict[word]=[]
elif word in st_dict:
st_dict[word].append(next_word)
else:
st_dict[word]=[next_word]
st_dict[words[-1]]=[]
print(st_dict)
However, any word that has punctuation in it should only have a null list as its value. However, I cannot get this to work. I have tried: word not in ['.','?'... etc] in addition to the if statement above, but words with punctuation in the middle of the string still append the next word as a value. How do I prevent this?
Thanks.
word in ['.','?']
will only be true if word
is exactly '.'
or exactly '?'
.
You want the opposite: '.' in word or '?' in word
.
If you have a list of punctuation then you should use any
:
punctuation = ".?"
any(punct in word for punct in punctuation)