2
$\begingroup$

I am trying to use CountVectorizer() in a loop, But I am getting an unexpected result. On the other hand, if I use it outside the loop then it works fine. I believe there is some small problem with the logic.

from sklearn.feature_extraction.text import CountVectorizer

keys_1 = ['funny', 'amusing', 'humorous', 'hilarious', 'jolly']
keys_2 = ['horror', 'fear', 'shock', 'panic', 'scream']
keys_3 = ['romantic', 'intimate', 'passionate', 'love', 'fond']

text = ('funny amusing fear passionate')

for i in range(3):
    keys = 'keys_' + str(i+1)
    cv = CountVectorizer(vocabulary = keys) 
    data = cv.fit_transform([text]).toarray()
    print(data)

cv1 = CountVectorizer(vocabulary = keys_1) 
data = cv1.fit_transform([text]).toarray()
print(data)

cv2 = CountVectorizer(vocabulary = keys_2) 
data = cv2.fit_transform([text]).toarray()
print(data)

cv3 = CountVectorizer(vocabulary = keys_3) 
data = cv3.fit_transform([text]).toarray()
print(data)

Output

[[0 0 0 0 0 0]]

[[0 0 0 0 0 0]]

[[0 0 0 0 0 0]]

[[1 1 0 0 0]]

[[0 1 0 0 0]]

[[0 0 1 0 0]]

$\endgroup$
1
$\begingroup$

The problem lies in the line:

keys = 'keys_' + str(i+1)

Here, keys becomes a string variable while I guess you would expect it to take the value of the list you defined in the first lines..

Try instead with a dictionary:

my_keys= {
"keys_1" : ['funny', 'amusing', 'humorous', 'hilarious', 'jolly'],
"keys_2" : ['horror', 'fear', 'shock', 'panic', 'scream'],
"keys_3" : ['romantic', 'intimate', 'passionate', 'love', 'fond']
}
text = ('funny amusing fear passionate')

for i in range(3):
    keys = my_keys['keys_' + str(i+1)]
    cv = CountVectorizer(vocabulary = keys) 
    data = cv.fit_transform([text]).toarray()
    print(data)
|improve this answer|||||
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.