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
26,851 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

different results for Random Forest Regression in R and Python

Random Forests, as others have mentioned, have ...READ MORE

answered Apr 12, 2022 in Machine Learning by Dev
• 6,000 points
1,124 views
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 4,056 views
0 votes
1 answer
+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,790 points
3,477 views
0 votes
1 answer

Python script for linear regression on panda dataframe

Use the following code: from scipy import stats slope, ...READ MORE

answered May 23, 2019 in Machine Learning by Imran
1,705 views
0 votes
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP