我的if / else语句直接转到其他地方,我似乎无法弄明白为什么。这是我的代码:
var sentiment = require ('sentiment');
var twitterSentiment;
var geoColor;
var results;
var twit = new twitter({
consumer_key: credentials.consumer_key,
consumer_secret: credentials.consumer_secret,
access_token_key: credentials.access_token_key,
access_token_secret: credentials.access_token_secret
});
twit.stream(
'statuses/filter',
{ 'locations': location },
function(stream) {
stream.on('data', function(tweet) {
console.log(tweet.text);
results = sentiment (tweet.text);
twitterSentiment = results;
//Comparison of Sentiment Scores
if (twitterSentiment == 0) {
geoColor = '#B5B5B5';
}
else if (twitterSentiment < 0) {
geoColor = '#FC0828';
}
else {
geoColor = '#00DE1E';
}
console.log (geoColor);
});
});
这是一个示例输出:
omg yes!!
#00DE1E
Do you think will actually understand? I want to ask mine the same question. Just not sure I'm ready to have that conversation.
#00DE1E
A thing of beauty by:
@youtube
#00DE1E
do you still do this??
#00DE1E
正如您所看到的,只有一种颜色可以识别所有推文;几乎好像我的if/else
语句没有正确实现?
当我将console.log (geoColor);
更改为console.log (results);
这是我的输出:
omg yes!!
{ score: 1,
comparative: 0.25,
tokens: [ 'omg', 'yes' ],
words: [ 'yes' ],
positive: [ 'yes' ],
negative: [] }
Do you think will actually understand? I want to ask mine the same question. Just not sure I'm ready to have that conversation.
{ score: 1,
comparative: 0.041666666666666664,
tokens:
[
'do',
'you',
'think',
'will',
'actually',
'understand',
'i',
'want',
'to',
'ask',
'mine',
'the',
'same',
'question',
'just',
'not',
'sure',
'i\'m',
'ready',
'to',
'have',
'that',
'conversation' ],
words: [ 'want' ],
positive: [ 'want' ],
negative: [] }
A thing of beauty by:
@youtube
{ score: 3,
comparative: 0.25,
tokens:
[ 'a',
'thing',
'of',
'beauty',
'by',
'youtube', ],
words: [ 'beauty' ],
positive: [ 'beauty' ],
negative: [] }
do you still do this??
{ score: 0,
comparative: 0,
tokens:
[
'do',
'you',
'still',
'do',
'this' ],
words: [],
positive: [],
negative: [] }
正如你所看到的,每条推文的个人情绪评分分别为1,1,3,0
那么为什么我的if / else语句忽略了这些数字呢?
我可以在代码中更改哪些内容,以便我的if / else语句正确实现并考虑推文的情绪分数?我的目标是为每条推文输出合适的颜色。
答案 0 :(得分:1)
您的var results
是一个对象,包含许多其他属性。在javascript中,“if”子句将始终为非null对象实例返回“true”。将对象与数字进行比较时 - 任何非基本对象的实例都将返回1
。
正如您所说,您想要比较score
属性的值,因此您需要做的是在if子句中引用results.score
。
更改为
twitterSentiment = results.score;
应该解决你的问题。
答案 1 :(得分:0)
您正在为结果对象设置twitterSentiment并比较整个对象而不仅仅是分数。将您的代码更改为:
if (twitterSentiment.score == 0) {
geoColor = '#B5B5B5';
}
else if (twitterSentiment.score < 0) {
geoColor = '#FC0828';
}
else {
geoColor = '#00DE1E';
}