偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

用戶失誤我“買單”:用戶輸入錯(cuò)誤了怎么辦?

開(kāi)發(fā) 后端
本文將為你提供幾種處理Python字典 keyerror的方法。去努力構(gòu)建一個(gè)python智能字典,它能幫你處理用戶的輸入錯(cuò)誤問(wèn)題。

本文轉(zhuǎn)載自公眾號(hào)“讀芯術(shù)”(ID:AI_Discovery)

[[324523]]

問(wèn)題來(lái)源于生活。上周在做業(yè)余項(xiàng)目時(shí),我遇到了一個(gè)非常有趣的設(shè)計(jì)問(wèn)題:“如果用戶輸入錯(cuò)誤了怎么辦?”如果輸入錯(cuò)誤,就會(huì)發(fā)生以下這種情況:

 

用戶失誤我“買單”:用戶輸入錯(cuò)誤了怎么辦?

 

 

示例:Python Dict

 

Python中的字典表示 鍵(keys)和值(values)。例如:

  1. student_grades = {'John': 'A','Mary': 'C', 'Rob': 'B'}# To check grade of John, we call 
  2. print(student_grades['John']) 
  3. # Output: A 

當(dāng)您試圖訪問(wèn)不存在的密鑰時(shí)會(huì)遇到什么情況?

  1. print(student_grades['Maple']) 
  2. # Output: 
  3. KeyError                         Traceback(most recent call last) 
  4. <ipython-input-6-51fec14f477a> in <module> 
  5. ----> print(student_grades['Maple']) 
  6.  
  7. KeyError: 'Maple' 

您會(huì)收到密匙錯(cuò)誤(KeyError)提示。

每當(dāng)dict()請(qǐng)求對(duì)象為字典中不存在的鍵(key)時(shí),就會(huì)發(fā)生KeyError。接收用戶輸入時(shí),此錯(cuò)誤十分常見(jiàn)。例如:

  1. student_name =input("Please enter student name: ") 
  2. print(student_grades[student_name]) 

本文將為你提供幾種處理Python字典 keyerror的方法。去努力構(gòu)建一個(gè)python智能字典,它能幫你處理用戶的輸入錯(cuò)誤問(wèn)題。

設(shè)置默認(rèn)值

一個(gè)非常簡(jiǎn)便的方法便是在請(qǐng)求的key不存在時(shí)返回默認(rèn)值??梢允褂胓et()方法完成此操作:

  1. default_grade = 'Not Available' 
  2. print(student_grades.get('Maple',default_grade))# Output: 
  3. # Not Available 

解決大小寫問(wèn)題

假設(shè)您構(gòu)建了Python字典,其中包含特定國(guó)家的人口數(shù)據(jù)。代碼將要求用戶輸入一個(gè)國(guó)家名并輸出顯示其人口數(shù)。

  1. # population in millions. (Source: https://www.worldometers.info/world-population/population-by-country/) 
  2.                                   population_dict= {'China':1439, 'India':1380, 'USA':331, 'France':65,'Germany':83, 'Spain':46} 
  3.                                                                                # getting userinput 
  4.                                   Country_Name=input('Please enterCountry Name: ') 
  5.                                                                                # access populationusing country name from dict 
  6.                                   print(population_dict[Country_Name]) 
  1. # Output 
  2. Please enter Country Name: France 
  3. 65 

然而,假設(shè)用戶輸入的是‘france’。目前,在我們的字典里,所有的鍵的首字母均是大寫形式。那么輸出內(nèi)容會(huì)是什么?

  1. Please enter Country Name:france-----------------------------------------------------------------KeyError                         Traceback (most recentcall last) 
  2. <ipython-input-6-51fec14f477a> in <module> 
  3.       2 Country_Name = input('Pleaseenter Country Name: ') 
  4.       3 
  5. ----> 4 print(population_dict[Country_Name]) 

 

  1. KeyError: 'france' 

由于‘france’不是字典中的鍵,因此會(huì)收到錯(cuò)誤提示。

 

[[324525]]

 

 

圖源:unsplash

 

一個(gè)簡(jiǎn)單的解決方法:用小寫字母存儲(chǔ)所有國(guó)家/地區(qū)名稱。另外,將用戶輸入的所有內(nèi)容轉(zhuǎn)換為小寫形式。

  1. # keys (Country Names) are now alllowercase 
  2.         population_dict = {'china':1439, 'india':1380, 'usa':331, 'france':65,'germany':83, 'spain':46} 
  3.         Country_Name=input('Please enterCountry Name: ').lower() # lowercase input 
  4.                     print(population_dict[Country_Name]) 
  1. Please enter Country Name:france 
  2. 65 

處理拼寫錯(cuò)誤

然而,假設(shè)用戶輸入的是 ‘Frrance’而不是 ‘France’。我們?cè)撊绾谓鉀Q此問(wèn)題?

一種方法是使用條件語(yǔ)句。

我們會(huì)檢查給定的用戶輸入是否可用作鍵(key)。如不可用,則輸出顯示一條消息。最好將其放入一個(gè)循環(huán)語(yǔ)句中,并在某特殊的標(biāo)志輸入上中斷(如exit)。

  1. population_dict = {'china':1439, 'india':1380, 'usa':331, 'france':65,'germany':83, 'spain':46} 
  2.                                                        while(True): 
  3.                             Country_Name=input('Please enterCountry Name(type exit to close): ').lower() 
  4.                             # break from code if user enters exit 
  5.                             ifCountry_Name=='exit': 
  6.                                 break 
  7.                                                            ifCountry_Nameinpopulation_dict.keys(): 
  8.                                 print(population_dict[Country_Name]) 
  9.                             else: 
  10.                                 print("Pleasecheck for any typos. Data not Available for ",Country_Name) 

循環(huán)將繼續(xù)運(yùn)行,直到用戶進(jìn)入exit。

優(yōu)化方法

雖然上述方法“有效”,但不夠“智能”。我們希望程序功能變強(qiáng)大,并能夠檢測(cè)到簡(jiǎn)單的拼寫錯(cuò)誤,例如frrance和chhina(類似于Google搜索)。

 

[[324526]]

 

 

圖源:unsplash

 

我找到了幾個(gè)適合解決key error的庫(kù),其中我最喜歡的是標(biāo)準(zhǔn)的python庫(kù):difflib。

difflib可用于比較文件、字符串、列表等,并生成各種形式的不同信息。該模塊提供了用于比較序列的各種類和函數(shù)。我們將使用difflib的兩個(gè)功能:SequenceMatcher 和 get_close_matches。讓我們簡(jiǎn)單地瀏覽下這兩種功能。

1. # SequenceMatcher

SequenceMatcher是difflib中的類,用于比較兩個(gè)序列。我們定義它的對(duì)象如下:

  1. difflib.SequenceMatcher(isjunk=None,a=''b=''autojunk=True
  • isjunk :在比較兩個(gè)文本塊時(shí)用于標(biāo)明不需要的垃圾元素(空白,換行符等)。從而禁止通過(guò)有問(wèn)題的文本。
  • a and b: 比較字符串。
  • autojunk :一種自動(dòng)將某些序列項(xiàng)視為垃圾項(xiàng)的啟發(fā)式方法。

讓我們使用SequenceMatcher比較chinna和china這兩個(gè)字符串:

  1. from difflib importSequenceMatcher# import 
  2.                                  # creating aSequenceMatcher object comparing two strings 
  3.               check =SequenceMatcher(None, 'chinna', 'china') 
  4.                                  # printing asimilarity ratio on a scale of 0(lowest) to 1(highest) 
  5.               print(check.ratio()) 
  6.               # Output 
  7.               #0.9090909090909091 

在以上代碼中,使用了ratio()方法。ratio返回序列相似度的度量,作為范圍[0,1]中的浮點(diǎn)值。

2. # get_close_matches

現(xiàn)提供一種基于相似性比較兩個(gè)字符串的方法。

如果我們希望找到與特定字符串相似的所有字符串(存儲(chǔ)于數(shù)據(jù)庫(kù)),會(huì)發(fā)生什么情況?

get_close_matches() 返回一個(gè)列表,其中包含可能性列表中的最佳匹配項(xiàng)。

  1. difflib.get_close_matches(word,possibilities, n=3cutoff=0.6) 
  • word:需要匹配的字符串。
  • possibilities: 匹配單詞的字符串列表。
  • Optional n: 要返回的最大匹配數(shù)。默認(rèn)情況下是3;且必須大于0。
  • Optional cutoff:相似度必須高于此值。默認(rèn)為0.6。

潛在的最佳n個(gè)匹配項(xiàng)將返回到一個(gè)列表中,并按相似度得分排序,最相似者優(yōu)先。

 

用戶失誤我“買單”:用戶輸入錯(cuò)誤了怎么辦?

 

 

圖源:unsplash

 

來(lái)看以下示例:

  1. from difflib importget_close_matches 
  2.                                      print(get_close_matches("chinna", ['china','france','india','usa'])) 
  3.                 # Output 
  4.                 # ['china'] 

匯總

既然可以使用difflib了,那么讓我們把所有內(nèi)容進(jìn)行組合,構(gòu)建一個(gè)防誤的python字典。

當(dāng)用戶提供的國(guó)家名不在population_dic.keys()中時(shí),需要格外注意。我們應(yīng)嘗試找到一個(gè)名稱與用戶輸入相似的國(guó)家,然后輸出其人口數(shù)。

  1. # pass country_name in word anddict keys in possibilities 
  2. maybe_country = get_close_matches(Country_Name, population_dict.keys())# Thenwe pick the first(most similar) string from the returned list 
  3. print(population_dict[maybe_country[0]]) 

最終代碼還需考慮其他一些情況。例如,如果沒(méi)有相似的字符串,或者未向用戶確認(rèn)這是否是所需字符串。如下:

  1. from difflib importget_close_matches 
  2.                 population_dict = {'china':1439, 'india':1380, 'usa':331, 'france':65,'germany':83, 'spain':46} 
  3.                                      while(True): 
  4.                     Country_Name=input('Please enterCountry Name(type exit to close): ').lower() 
  5.                     # break from code if user enters exit 
  6.                     ifCountry_Name=='exit': 
  7.                         break 
  8.                                          ifCountry_Nameinpopulation_dict.keys(): 
  9.                         print(population_dict[Country_Name]) 
  10.                     else: 
  11.                         # look for similarstrings 
  12.                         maybe_country =get_close_matches(Country_Name,population_dict.keys()) 
  13.                         if maybe_country == []:  # no similar string 
  14.                             print("Pleasecheck for any typos. Data not Available for ",Country_Name) 
  15.                         else: 
  16.                             # user confirmation 
  17.                             ans =input("Do youmean %s? Type y or n."% maybe_country[0]) 
  18.                             if ans =='y': 
  19.                                 # if y, returnpopulation 
  20.                                 print(population_dict[maybe_country[0]]) 
  21.                             else: 
  22.                                 # if n, start again 
  23.                                 print("Bad input.Try again.") 

輸出:

用戶失誤我“買單”:用戶輸入錯(cuò)誤了怎么辦?

Inida 其實(shí)是India.

這樣一來(lái),用戶的大小寫混淆或是輸入錯(cuò)誤的處理就不在話下了。你還可以進(jìn)一步研究其他各種應(yīng)用程序,比如使用NLPs 更好地理解用戶輸入,并在搜索引擎中顯示相似結(jié)果。Python智能字典的構(gòu)建方法,你學(xué)會(huì)了嗎?

 

責(zé)任編輯:趙寧寧 來(lái)源: 今日頭條
相關(guān)推薦

2013-12-17 16:41:06

安卓4.4.2隱私保護(hù)谷歌

2010-05-20 16:08:01

亞馬遜故障

2013-08-07 09:43:28

2017-06-30 13:23:59

SaaS供應(yīng)商破產(chǎn)

2020-03-09 14:05:27

數(shù)據(jù)庫(kù)工具技術(shù)

2021-02-22 17:13:47

HTTP1.1協(xié)議

2018-08-20 19:39:14

區(qū)塊鏈職業(yè)崗位

2022-05-17 07:35:13

安全Session

2011-02-22 11:23:04

vsftpd

2019-12-17 16:39:55

輸入法Windows 10Windows

2019-06-06 10:04:45

重構(gòu)代碼原代碼

2022-02-06 00:16:53

加密貨幣比特幣以太坊

2018-03-21 11:14:22

云計(jì)算云計(jì)算提供商數(shù)據(jù)

2009-04-09 09:16:19

微軟失誤緊急聲明

2020-12-21 15:40:25

技術(shù)研發(fā)管理

2017-07-04 15:07:44

Windows 7Windows數(shù)據(jù)錯(cuò)誤

2020-06-23 14:24:05

2G網(wǎng)絡(luò)中國(guó)聯(lián)通用戶

2021-01-04 09:40:48

Linux運(yùn)維Linux系統(tǒng)

2019-06-24 15:21:05

Git操作修改

2021-10-20 22:47:17

Windows 10Windows微軟
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)