You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python结合sklearn RandomForestClassifier的if elif语句失效问题

问题原因

你的问题出在条件判断的逻辑写法错误上。第一个if语句的条件:

if refined_predicted_input == 'youtube search' or 'search youtube':

在Python中,or运算符两侧需要是完整的布尔表达式。这里'search youtube'是一个非空字符串,会被Python判定为True,所以不管refined_predicted_input的值是什么,整个条件都会被判定为True,导致第一个分支永远执行。

修正方案

你需要把条件改成完整的比较表达式,或者用in来简化判断:

方案1:完整布尔表达式

if refined_predicted_input == 'youtube search' or refined_predicted_input == 'search youtube':

方案2:用in判断成员关系(更简洁)

if refined_predicted_input in ['youtube search', 'search youtube']:

同样,第二个elif的条件也需要做相同修正:

elif refined_predicted_input in ['google search', 'search google']:
修正后的完整代码
try: 
    predicted_user_input = rfc.predict(np.reshape(to_put_in_rfc, (1, -1)))
    print(predicted_user_input)

    print("RFC succesfully predicted\n")

    refined_predicted_input = predicted_user_input[0]
    print(refined_predicted_input)
except:
    print("RFC failed to predict\n")


if refined_predicted_input in ['youtube search', 'search youtube']:
    try:
        what_to_watch = input("Please enter what you would like to watch: ")
        youtubeSearch(what_to_watch=what_to_watch)
        print('Youtube search successfully executed')
    except:
        print("Youtube search failed")

elif refined_predicted_input in ['google search', 'search google']:
    try:
        what_to_search_for = input("Please enter what would you like to search for: ")
        googleSearch(what_to_search_for)
        print("Google search successfull")
    except:
        print("Google search failed")

elif refined_predicted_input == 'news search':
    news_to_search = input("Enter the topic of news you want to hear about: ")
    voice.say(newsSearch(news_to_search))

内容的提问来源于stack exchange,提问作者theThickProgrammer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 13:21:00