主頁 >  其他 > 如何正確使用其他函式/方法中回傳的變數?

如何正確使用其他函式/方法中回傳的變數?

2021-11-26 03:09:45 其他

因為我剛剛開始學習編碼,所以請不要打擾我,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' 未定義”,但我只是不知道如何訪問該變數和我已經嘗試了所有我知道我可以嘗試的方法......我被困在這里并且有點沮喪,因為我知道這是一個菜鳥錯誤,但在兩周的壓力和沮喪之后我仍然無法掌握它。

歡迎任何反饋。

uj5u.com熱心網友回復:

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個元素是每個變數的值的元組,并且該元組被分配給resres = analise_and_explain_results(user_input, man_coded_bag, woman_coded_bag)

所謂變數的值strengths_of_coding作為函式內部可res[2]get_results以后你做的分配res

uj5u.com熱心網友回復:

因此,如果您對 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那樣組合它們

uj5u.com熱心網友回復:

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].

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/365870.html

標籤:Python 功能 方法

上一篇:將檔案的列乘以指數函式

下一篇:使模型功能停止計數

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 網閘典型架構簡述

    網閘架構一般分為兩種:三主機的三系統架構網閘和雙主機的2+1架構網閘。 三主機架構分別為內端機、外端機和仲裁機。三機無論從軟體和硬體上均各自獨立。首先從硬體上來看,三機都用各自獨立的主板、記憶體及存盤設備。從軟體上來看,三機有各自獨立的作業系統。這樣能達到完全的三機獨立。對于“2+1”系統,“2”分為 ......

    uj5u.com 2020-09-10 02:00:44 more
  • 如何從xshell上傳檔案到centos linux虛擬機里

    如何從xshell上傳檔案到centos linux虛擬機里及:虛擬機CentOs下執行 yum -y install lrzsz命令,出現錯誤:鏡像無法找到軟體包 前言 一、安裝lrzsz步驟 二、上傳檔案 三、遇到的問題及解決方案 總結 前言 提示:其實很簡單,往虛擬機上安裝一個上傳檔案的工具 ......

    uj5u.com 2020-09-10 02:00:47 more
  • 一、SQLMAP入門

    一、SQLMAP入門 1、判斷是否存在注入 sqlmap.py -u 網址/id=1 id=1不可缺少。當注入點后面的引數大于兩個時。需要加雙引號, sqlmap.py -u "網址/id=1&uid=1" 2、判斷文本中的請求是否存在注入 從文本中加載http請求,SQLMAP可以從一個文本檔案中 ......

    uj5u.com 2020-09-10 02:00:50 more
  • Metasploit 簡單使用教程

    metasploit 簡單使用教程 浩先生, 2020-08-28 16:18:25 分類專欄: kail 網路安全 linux 文章標簽: linux資訊安全 編輯 著作權 metasploit 使用教程 前言 一、Metasploit是什么? 二、準備作業 三、具體步驟 前言 Msfconsole ......

    uj5u.com 2020-09-10 02:00:53 more
  • 游戲逆向之驅動層與用戶層通訊

    驅動層代碼: #pragma once #include <ntifs.h> #define add_code CTL_CODE(FILE_DEVICE_UNKNOWN,0x800,METHOD_BUFFERED,FILE_ANY_ACCESS) /* 更多游戲逆向視頻www.yxfzedu.com ......

    uj5u.com 2020-09-10 02:00:56 more
  • 北斗電力時鐘(北斗授時服務器)讓網路資料更精準

    北斗電力時鐘(北斗授時服務器)讓網路資料更精準 北斗電力時鐘(北斗授時服務器)讓網路資料更精準 京準電子科技官微——ahjzsz 近幾年,資訊技術的得了快速發展,互聯網在逐漸普及,其在人們生活和生產中都得到了廣泛應用,并且取得了不錯的應用效果。計算機網路資訊在電力系統中的應用,一方面使電力系統的運行 ......

    uj5u.com 2020-09-10 02:01:03 more
  • 【CTF】CTFHub 技能樹 彩蛋 writeup

    ?碎碎念 CTFHub:https://www.ctfhub.com/ 筆者入門CTF時時剛開始刷的是bugku的舊平臺,后來才有了CTFHub。 感覺不論是網頁UI設計,還是題目質量,賽事跟蹤,工具軟體都做得很不錯。 而且因為獨到的金幣制度的確讓人有一種想去刷題賺金幣的感覺。 個人還是非常喜歡這個 ......

    uj5u.com 2020-09-10 02:04:05 more
  • 02windows基礎操作

    我學到了一下幾點 Windows系統目錄結構與滲透的作用 常見Windows的服務詳解 Windows埠詳解 常用的Windows注冊表詳解 hacker DOS命令詳解(net user / type /md /rd/ dir /cd /net use copy、批處理 等) 利用dos命令制作 ......

    uj5u.com 2020-09-10 02:04:18 more
  • 03.Linux基礎操作

    我學到了以下幾點 01Linux系統介紹02系統安裝,密碼啊破解03Linux常用命令04LAMP 01LINUX windows: win03 8 12 16 19 配置不繁瑣 Linux:redhat,centos(紅帽社區版),Ubuntu server,suse unix:金融機構,證券,銀 ......

    uj5u.com 2020-09-10 02:04:30 more
  • 05HTML

    01HTML介紹 02頭部標簽講解03基礎標簽講解04表單標簽講解 HTML前段語言 js1.了解代碼2.根據代碼 懂得挖掘漏洞 (POST注入/XSS漏洞上傳)3.黑帽seo 白帽seo 客戶網站被黑帽植入劫持代碼如何處理4.熟悉html表單 <html><head><title>TDK標題,描述 ......

    uj5u.com 2020-09-10 02:04:36 more
最新发布
  • 2023年最新微信小程式抓包教程

    01 開門見山 隔一個月發一篇文章,不過分。 首先回顧一下《微信系結手機號資料庫被脫庫事件》,我也是第一時間得知了這個訊息,然后跟蹤了整件事情的經過。下面是這起事件的相關截圖以及近日流出的一萬條資料樣本: 個人認為這件事也沒什么,還不如關注一下之前45億快遞資料查詢渠道疑似在近日復活的訊息。 訊息是 ......

    uj5u.com 2023-04-20 08:48:24 more
  • web3 產品介紹:metamask 錢包 使用最多的瀏覽器插件錢包

    Metamask錢包是一種基于區塊鏈技術的數字貨幣錢包,它允許用戶在安全、便捷的環境下管理自己的加密資產。Metamask錢包是以太坊生態系統中最流行的錢包之一,它具有易于使用、安全性高和功能強大等優點。 本文將詳細介紹Metamask錢包的功能和使用方法。 一、 Metamask錢包的功能 數字資 ......

    uj5u.com 2023-04-20 08:47:46 more
  • vulnhub_Earth

    前言 靶機地址->>>vulnhub_Earth 攻擊機ip:192.168.20.121 靶機ip:192.168.20.122 參考文章 https://www.cnblogs.com/Jing-X/archive/2022/04/03/16097695.html https://www.cnb ......

    uj5u.com 2023-04-20 07:46:20 more
  • 從4k到42k,軟體測驗工程師的漲薪史,給我看哭了

    清明節一過,盲猜大家已經無心上班,在數著日子準備過五一,但一想到銀行卡里的余額……瞬間心情就不美麗了。最近,2023年高校畢業生就業調查顯示,本科畢業月平均起薪為5825元。調查一出,便有很多同學表示自己又被平均了。看著這一資料,不免讓人想到前不久中國青年報的一項調查:近六成大學生認為畢業10年內會 ......

    uj5u.com 2023-04-20 07:44:00 more
  • 最新版本 Stable Diffusion 開源 AI 繪畫工具之中文自動提詞篇

    🎈 標簽生成器 由于輸入正向提示詞 prompt 和反向提示詞 negative prompt 都是使用英文,所以對學習母語的我們非常不友好 使用網址:https://tinygeeker.github.io/p/ai-prompt-generator 這個網址是為了讓大家在使用 AI 繪畫的時候 ......

    uj5u.com 2023-04-20 07:43:36 more
  • 漫談前端自動化測驗演進之路及測驗工具分析

    隨著前端技術的不斷發展和應用程式的日益復雜,前端自動化測驗也在不斷演進。隨著 Web 應用程式變得越來越復雜,自動化測驗的需求也越來越高。如今,自動化測驗已經成為 Web 應用程式開發程序中不可或缺的一部分,它們可以幫助開發人員更快地發現和修復錯誤,提高應用程式的性能和可靠性。 ......

    uj5u.com 2023-04-20 07:43:16 more
  • CANN開發實踐:4個DVPP記憶體問題的典型案例解讀

    摘要:由于DVPP媒體資料處理功能對存放輸入、輸出資料的記憶體有更高的要求(例如,記憶體首地址128位元組對齊),因此需呼叫專用的記憶體申請介面,那么本期就分享幾個關于DVPP記憶體問題的典型案例,并給出原因分析及解決方法。 本文分享自華為云社區《FAQ_DVPP記憶體問題案例》,作者:昇騰CANN。 DVPP ......

    uj5u.com 2023-04-20 07:43:03 more
  • msf學習

    msf學習 以kali自帶的msf為例 一、msf核心模塊與功能 msf模塊都放在/usr/share/metasploit-framework/modules目錄下 1、auxiliary 輔助模塊,輔助滲透(埠掃描、登錄密碼爆破、漏洞驗證等) 2、encoders 編碼器模塊,主要包含各種編碼 ......

    uj5u.com 2023-04-20 07:42:59 more
  • Halcon軟體安裝與界面簡介

    1. 下載Halcon17版本到到本地 2. 雙擊安裝包后 3. 步驟如下 1.2 Halcon軟體安裝 界面分為四大塊 1. Halcon的五個助手 1) 影像采集助手:與相機連接,設定相機引數,采集影像 2) 標定助手:九點標定或是其它的標定,生成標定檔案及內參外參,可以將像素單位轉換為長度單位 ......

    uj5u.com 2023-04-20 07:42:17 more
  • 在MacOS下使用Unity3D開發游戲

    第一次發博客,先發一下我的游戲開發環境吧。 去年2月份買了一臺MacBookPro2021 M1pro(以下簡稱mbp),這一年來一直在用mbp開發游戲。我大致分享一下我的開發工具以及使用體驗。 1、Unity 官網鏈接: https://unity.cn/releases 我一般使用的Apple ......

    uj5u.com 2023-04-20 07:40:19 more