【问题标题】:How can I properly use variables returned in other function / method?如何正确使用其他函数/方法中返回的变量?
【发布时间】:2022-01-03 17:48:50
【问题描述】:

由于我刚刚开始学习编码,请与我交谈,Python 是我学习的第一门语言。我是一个自学成才的人,目前设法在一家初创公司找到了实习机会。他们让我为他们的网站制作一个聊天机器人,我已经设法使用了一个开源聊天机器人,使用 NLTK 和 Tensorflow,使其适应我们的需求,并为其添加了一些新东西,仅此而已。也设法部署了它,现在已经成功运行了一个多月。依此类推,我正在从事第二个项目,我决定从头开始构建,因为它并不复杂,但我在 OOP 方面遇到了很多困难,无法真正理解这些功能是如何工作的,以我可以的方式制作一个单独的函数,它会做它应该做的事情,但是我返回的变量,当我在另一个函数中需要它时,我无法设法调用或使用它。有人可以帮我理解它的深度吗? 这是我从聊天机器人项目中提取的一些代码,不是我构建的代码,也绝对不是我完全知道如何构建自己的代码,而是我理解并能够根据我的需要进行编辑的代码。我现在尝试从我正在从事的新项目中构建函数结构时得到启发。

def clean_up_sentence(sentence):
    sentence_words = nltk.word_tokenize(sentence)
    sentence_words = [lemmatizer.lemmatize(word.lower()) for word in sentence_words]
    return sentence_words


def chatbot_response(msg):
    print("Message: %s" % msg)
    ints = predict_class(msg, model)
    if len(ints) == 0:
        return "Undskyld, kan ikke forstå dig. Prøv at stille et andet spørgsmål."
    res = getResponse(ints[0])
    if len(res) == 0:
        return "Undskyld, kan ikke forstå dig. Prøv at stille et andet spørgsmål."
    return res


def getResponse(intent):
    tag = intent["intent"]

    for i in list_of_intents:
        if i["tag"] == tag:
            return random.choice(i["responses"])


def bow(sentence, words, show_details=True):
    sentence_words = clean_up_sentence(sentence)
    bag = [0] * len(words)
    for s in sentence_words:
        for i, w in enumerate(words):
            if w == s:
                bag[i] = 1
                if show_details:
                    print("found in bag: %s" % w)
    return np.array(bag)


def predict_class(sentence, model):
    p = bow(sentence, words, show_details=False)
    res = model.predict(np.array([p]))[0]
    ERROR_THRESHOLD = 0.9
    before_filtering = [[i, r] for i, r in enumerate(res) if r > 0.0]
    results = [[i, r] for i, r in enumerate(res) if r > ERROR_THRESHOLD]
    # sort by strength of probability
    before_filtering.sort(key=lambda x: x[1], reverse=True)
    results.sort(key=lambda x: x[1], reverse=True)
    return_list = []
    for r in results:
        return_list.append({"intent": classes[r[0]], "probability": str(r[1])})
    before_filtering_list = []
    for r in before_filtering:
        before_filtering_list.append(
            {"intent": classes[r[0]], "probability": str(r[1])}
        )
    print("Before filtering: %s" % before_filtering_list[:3])
    print("After filtering: %s" % return_list)
    return return_list

这是我在我正在从事的新项目中尝试的,与聊天机器人完全无关。我的代码不起作用,我无法理解如何连接这些方法以及为什么要以这种方式连接。

 man_coded_bag = []
woman_coded_bag = []

feminine_coded_words = [
    "agree",
    "affectionate",
    "child",
    "cheer",
    "collab",
    "commit",
    "communal",
    "compassion",
    "connect",
    "considerate",
    "cooperat",
    "co-operat",
    "depend",
    "emotiona",
    "empath",
    "feel",
    "flatterable",
    "gentle",
    "honest",
    "interpersonal",
    "interdependen",
    "interpersona",
    "inter-personal",
    "inter-dependen",
    "inter-persona",
    "kind",
    "kinship",
    "loyal",
    "modesty",
    "nag",
    "nurtur",
    "pleasant",
    "polite",
    "quiet",
    "respon",
    "sensitiv",
    "submissive",
    "support",
    "sympath",
    "tender",
    "together",
    "trust",
    "understand",
    "warm",
    "whin",
    "enthusias",
    "inclusive",
    "yield",
    "share",
    "sharin"
]

masculine_coded_words = [
    "active",
    "adventurous",
    "aggress",
    "ambitio",
    "analy",
    "assert",
    "athlet",
    "autonom",
    "battle",
    "boast",
    "challeng",
    "champion",
    "compet",
    "confident",
    "courag",
    "decid",
    "decision",
    "decisive",
    "defend",
    "determin",
    "domina",
    "dominant",
    "driven",
    "fearless",
    "fight",
    "force",
    "greedy",
    "head-strong",
    "headstrong",
    "hierarch",
    "hostil",
    "impulsive",
    "independen",
    "individual",
    "intellect",
    "lead",
    "logic",
    "objective",
    "opinion",
    "outspoken",
    "persist",
    "principle",
    "reckless",
    "self-confiden",
    "self-relian",
    "self-sufficien",
    "selfconfiden",
    "selfrelian",
    "selfsufficien",
    "stubborn",
    "superior",
    "unreasonab"
]

explanations = {
    "feminine-coded": (
        "This job ad uses more words that are subtly coded as feminine than words that are subtly coded as masculine (according to the research). Fortunately, the research suggests this will have only a slight effect on how appealing the job is to men, and will encourage women applicants."
    ),
    "masculine-coded": (
        "This job ad uses more words that are subtly coded as masculine than words that are subtly coded as feminine (according to the research). It risks putting women off applying, but will probably encourage men to apply."
    ),
    "strongly feminine-coded": (
        "This job ad uses more words that are subtly coded as feminine than words that are subtly coded as masculine (according to the research). Fortunately, the research suggests this will have only a slight effect on how appealing the job is to men, and will encourage women applicants."
    ),
    "strongly masculine-coded": (
        "This job ad uses more words that are subtly coded as masculine than words that are subtly coded as feminine (according to the research). It risks putting women off applying, but will probably encourage men to apply."
    ),
    "empty": (
        "This job ad doesn't use any words that are subtly coded as masculine or feminine (according to the research). It probably won't be off-putting to men or women applicants."
    ),
    "neutral": (
        "This job ad uses an equal number of words that are subtly coded as masculine and feminine (according to the research). It probably won't be off-putting to men or women applicants."
    ),
}


def men_coded_words(masc_bag, text):
    add_text = text
    man_coded_bag = masc_bag
    for word in masculine_coded_words:
        if word in add_text:
            man_coded_bag.append(word)    
    return man_coded_bag


def women_coded_words(fem_bag, text):
    add_text = text
    woman_coded_bag = fem_bag
    for word in feminine_coded_words:
        if word in add_text:
            woman_coded_bag.append(word)
    return woman_coded_bag


def analise_and_explain_results(text, count_man, count_fem):
 
    count_man_words = count_man
    count_man_words = len(man_coded_bag)

    count_woman_words = count_fem
    count_woman_words = len(woman_coded_bag)

    coding_score = count_woman_words - count_man_words

    strengths_of_coding = ""

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

    return count_man_words, count_woman_words, strengths_of_coding


def get_results(text):
    user_input = text
    user_input = input("add text here:").lower()

    res = analise_and_explain_results(user_input, man_coded_bag, woman_coded_bag)

    # i am trying to use the returned variable strengths_of_coding and is not available.
    explain_results = explanations[strengths_of_coding]

    return res, explain_results

get_results("random text added here, really whatever for testing purposes")

是的,所以当我调用 get_results('text') 时,我收到了这个错误,我知道它来自哪里,“名称 'strengths_of_coding' 未定义”,但我只是不知道如何访问那个变量,我已经尝试了所有我知道我可以尝试的东西......我被困在这里并且有点沮丧,因为我知道这是一个菜鸟错误,但在两周的压力之后我仍然无法掌握它和沮丧。

欢迎任何反馈。

【问题讨论】:

  • 我没有看到您调用 get_results 的代码...
  • 就在最后一行代码之后,我将编辑我的帖子并添加它。

标签: python function methods


【解决方案1】:

strengths_of_coding 仅在 analise_and_explain_results 函数内部定义。当您返回该函数的值时,它们不再附加到您在函数中使用的名称

return count_man_words, count_woman_words, strengths_of_coding 也可以写成return (count_man_words, count_woman_words, strengths_of_coding) - 这意味着函数的返回值是一个元组,其中包含 3 个元素是每个变量的值,并且该元组在 @987654326 中分配给 res @

res进行赋值后,函数内名为strengths_of_coding的变量的值在get_results中可作为res[2]使用

【讨论】:

    【解决方案2】:

    因此,如果您几乎没有任何 OOP 或一般编码方面的知识,就很难解释所有内容。但是在python中,函数的返回值可以是任何东西。 None,整数、列表、元组、字典、对象。甚至可以是一个类定义。只有看它,你才能确切地知道。这就是所谓的鸭式打字; “如果它走路像鸭子,叫起来像鸭子,那它一定是鸭子”

    在这种情况下,您的 analise_and_explain_results 函数不会返回 一个 东西,而是返回几个,因为它这样做了:

    return count_man_words, count_woman_words, strengths_of_coding
    

    所以它实际上返回了一个包含这三个值的元组。这些变量是作用域到那个特定函数的,你不能再在那个函数之外使用它们了。 注意:为简单起见;让我们坚持不要在函数之外使用它们,因为这是不好的做法。

    然后在您的代码中执行以下操作:

    res = analise_and_explain_results(user_input, man_coded_bag, woman_coded_bag)
    

    这意味着此时res 实际上是包含您感兴趣的三个值的元组。您有几种方法可以解决这个问题。但最简单的方法是像这样分配变量的值:

    count_man_words, count_woman_words, strengths_of_coding = analise_and_explain_results(user_input, man_coded_bag, woman_coded_bag)
    

    这基本上将元组解包成三个不同的值,因为它基本上是这样做的:

    a, b, c = (1, 2 ,3)
    

    你之前在哪里:

    d = (1, 2, 3)
    

    拆包很容易,只要您拆包的物品包含您要分配的物品数量即可;

    a, b, c = d
    

    如果您在掌握 OOP 和 python 方面有困难,我建议您在跑步之前先学会走路,现在 IMO 正在这样做。 遵循一些解释 OOP 和 python 的教程或视频。或者像在realpython 上那样组合它们。

    【讨论】:

    • 谢谢,您的反馈很有价值。我想将所有变量打包在一个 json 对象中并将它们返回给前端以突出显示文本中的单词和类似的东西,所以我需要它们。感谢您的评论,我更了解如何使用它们。
    • 在我使用您的指导修复我的错误后,回到这里试图向您解释我正在寻找的实际答案是什么,我最终在将我的问题表述为时从不同的角度看待尽可能清楚。在这样做的同时,我设法看到了我对功能的理解需要澄清的地方。您的评论帮助我修复了我的错误,从不同的角度看待函数,这让我找到了我正在寻找的其他答案。我会将其标记为正确答案,但我没有足够的声誉来支持它。感谢您的宝贵时间。
    【解决方案3】:

    res = analise_and_explain_results(user_input, man_coded_bag, woman_coded_bag)res 变成一个包含 3 个元素的元组。 strengths_of_coding 是这个元组中的第三个元素。因此,您以res[2] 的身份访问它。在 python 中,当您将多个内容返回给一个变量时,该变量会变成一个元组。您可以提供多个变量来获取每个回报。例如,count_man_words, count_woman_words, strengths_of_coding = analise_and_explain_results(user_input, man_coded_bag, woman_coded_bag)。或者,如果您只需要返回一个,那么strengths_of_coding = analise_and_explain_results(user_input, man_coded_bag, woman_coded_bag)[2]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-10
      • 1970-01-01
      • 1970-01-01
      • 2015-08-16
      • 2015-05-06
      相关资源
      最近更新 更多