Python error TypeError unsupported operand type s for - list and int

0 votes

I am trying to understand the markov chain. This is my code:

import numpy as np
import random as rm
#import io

trump = open('C:\Users\sharma\PycharmProjects\machine-learning\speeches.txt').read()
# display the data
#print(trump)

#split the data
corpus = trump.split()
#print(corpus)

#Make pairs
def make_pairs(corpus):
    for i in range(len(corpus) - 1):
        yield (corpus[i] , corpus[i + 1])
pairs = make_pairs(corpus)

#append dictionary
word_dict = {}
for word1, word2 in pairs:
    if word1 in word_dict:
        word_dict[word1].append(word2)
    else:
        word_dict[word1] = [word2]

#Randomly pick first word
first_word = np.random.choice(corpus)
while first_word.islower():
    chain = [first_word]
    n_words = 20
    for i in range(n_words):
        chain.append(np.random.choice(word_dict[chain - 1]))
        print (' '.join(chain))

Ending up with the following error:

chain.append(np.random.choice(word_dict[chain - 1]))
TypeError: unsupported operand type(s) for -: 'list' and 'int'
Aug 2, 2019 in Machine Learning by Sharma
19,005 views

1 answer to this question.

0 votes

Hey, look at your code's second last line, you are trying to subtract an integer from a list which is obviously wrong.

According to your logic, I think this is what you are looking for:

chain.append(np.random.choice(word_dict[chain[-1]]))


Hope this helps!!

If you need to learn more about Python, It's recommended to join Python Online Training today.

Thanks!

answered Aug 2, 2019 by Naman

Related Questions In Machine Learning

0 votes
1 answer
0 votes
1 answer
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 2,405 views
0 votes
0 answers
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,810 points
1,806 views
0 votes
1 answer
0 votes
1 answer