因為我剛剛開始學習編碼,所以請不要打擾我,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個元素是每個變數的值的元組,并且該元組被分配給res在res = 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
上一篇:將檔案的列乘以指數函式
下一篇:使模型功能停止計數
