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

Python如何正确使用其他函数/方法返回的变量

解决方案

直接报错原因

你在analise_and_explain_results函数内部定义的strengths_of_coding属于局部变量,仅能在该函数内部访问,出了函数作用域就会失效。你已经把它作为返回值的第三个元素打包进了元组res,只需要把返回值拆包提取对应元素即可。

修正get_results里的对应代码即可解决报错:

# 拆包接收返回的三个值
count_man_words, count_woman_words, strengths_of_coding = analise_and_explain_results(text, man_coded_bag, woman_coded_bag)

其他需要修正的代码问题

你的代码还存在几个隐藏问题,不修复仍然会运行报错:

  • explanations字典缺失闭合的右大括号,同时缺少neutral、empty两种结果对应的解释,会触发KeyError
  • 你定义的全局列表名manly_coded_bag、female_coded_bag和后续使用的man_coded_bag、woman_coded_bag变量名不一致
  • 统计编码词的两个函数men_coded_words、women_coded_words从未被调用,统计列表永远为空
  • get_results里用input覆盖了传入的text参数,逻辑冲突可以按需删掉不需要的部分

完整可运行修正代码

feminine_coded_words = [
    "agree",
    "affectionate",
    "child",
    "cheer",
]

masculine_coded_words = [
    "active",
    "adventurous",
    "aggressive",
    "ambitios",
]

explanations = {
    "feminine-coded": "该招聘广告使用的女性隐性编码词数量多于男性隐性编码词",
    "masculine-coded": "该招聘广告使用的男性隐性编码词数量多于女性隐性编码词",
    "neutral": "该招聘广告使用的男女隐性编码词数量均衡",
    "empty": "该招聘广告不含性别隐性编码词"
}


def men_coded_words(text):
    man_coded_bag = []
    for word in masculine_coded_words:
        if word in text.lower():
            man_coded_bag.append(word)    
    return man_coded_bag


def women_coded_words(text):
    woman_coded_bag = []
    for word in feminine_coded_words:
        if word in text.lower():
            woman_coded_bag.append(word)
    return woman_coded_bag


def analise_and_explain_results(man_coded_bag, woman_coded_bag):
    count_man_words = len(man_coded_bag)
    count_woman_words = len(woman_coded_bag)
    coding_score = count_woman_words - count_man_words

    if coding_score == 0:
        strengths_of_coding = "neutral" if count_man_words else "empty"
    elif coding_score > 0:
        strengths_of_coding = "feminine-coded"
    else:
        strengths_of_coding = "masculine-coded"

    return count_man_words, count_woman_words, strengths_of_coding


def get_results(text):
    man_coded_bag = men_coded_words(text)
    woman_coded_bag = women_coded_words(text)
    count_man, count_fem, strengths_of_coding = analise_and_explain_results(man_coded_bag, woman_coded_bag)
    explain_results = explanations[strengths_of_coding]
    return (count_man, count_fem, strengths_of_coding), explain_results

# 测试调用
print(get_results("aggressive active child cheer"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 12:27:07