成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

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

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

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

[[324523]]

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

 

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

 

 

示例: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)您試圖訪問不存在的密鑰時會遇到什么情況?

  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' 

您會收到密匙錯誤(KeyError)提示。

每當(dāng)dict()請求對象為字典中不存在的鍵(key)時,就會發(fā)生KeyError。接收用戶輸入時,此錯誤十分常見。例如:

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

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

設(shè)置默認值

一個非常簡便的方法便是在請求的key不存在時返回默認值。可以使用get()方法完成此操作:

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

解決大小寫問題

假設(shè)您構(gòu)建了Python字典,其中包含特定國家的人口數(shù)據(jù)。代碼將要求用戶輸入一個國家名并輸出顯示其人口數(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)容會是什么?

  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’不是字典中的鍵,因此會收到錯誤提示。

 

[[324525]]

 

 

圖源:unsplash

 

一個簡單的解決方法:用小寫字母存儲所有國家/地區(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 

處理拼寫錯誤

然而,假設(shè)用戶輸入的是 ‘Frrance’而不是 ‘France’。我們該如何解決此問題?

一種方法是使用條件語句。

我們會檢查給定的用戶輸入是否可用作鍵(key)。如不可用,則輸出顯示一條消息。最好將其放入一個循環(huán)語句中,并在某特殊的標(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ù)運行,直到用戶進入exit。

優(yōu)化方法

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

 

[[324526]]

 

 

圖源:unsplash

 

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

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

1. # SequenceMatcher

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

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

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

  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]中的浮點值。

2. # get_close_matches

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

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

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

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

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

 

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

 

 

圖源:unsplash

 

來看以下示例:

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

匯總

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

當(dāng)用戶提供的國家名不在population_dic.keys()中時,需要格外注意。我們應(yīng)嘗試找到一個名稱與用戶輸入相似的國家,然后輸出其人口數(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]]) 

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

  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.") 

輸出:

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

Inida 其實是India.

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

 

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

2013-12-17 16:41:06

安卓4.4.2隱私保護谷歌

2010-05-20 16:08:01

亞馬遜故障

2013-08-07 09:43:28

2020-03-09 14:05:27

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

2017-06-30 13:23:59

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

2018-08-20 19:39:14

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

2021-02-22 17:13:47

HTTP1.1協(xié)議

2022-05-17 07:35:13

安全Session

2011-02-22 11:23:04

vsftpd

2009-04-09 09:16:19

微軟失誤緊急聲明

2022-02-06 00:16:53

加密貨幣比特幣以太坊

2019-12-17 16:39:55

輸入法Windows 10Windows

2019-06-06 10:04:45

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

2020-12-21 15:40:25

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

2018-03-21 11:14:22

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

2017-07-04 15:07:44

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

2020-06-23 14:24:05

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

2021-01-04 09:40:48

Linux運維Linux系統(tǒng)

2021-10-20 22:47:17

Windows 10Windows微軟

2018-06-11 15:20:24

點贊
收藏

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

主站蜘蛛池模板: 日韩不卡一区二区三区 | 欧美在线视频a | h视频在线免费看 | 国产麻豆乱码精品一区二区三区 | 久久久久久久久国产精品 | 亚洲日韩中文字幕一区 | 成人精品国产一区二区4080 | av国产在线观看 | 亚洲国产精品久久久久秋霞不卡 | 久草在线青青草 | www.v888av.com | 伊人色综合久久天天五月婷 | 久久精品91久久久久久再现 | 欧美日高清视频 | 午夜亚洲 | 久久国产精品无码网站 | www.亚洲| 一级看片 | 精品一区二区三区不卡 | 日韩av电影院| 欧美成人一区二区 | 99热在线免费 | 国产一级在线 | 日韩欧美在线视频观看 | 日韩av在线不卡 | 久草在线影 | 国产在线一区二 | 亚洲精视频 | 国产精品视屏 | 亚洲欧美在线免费观看 | 欧美 日韩 在线播放 | 凹凸日日摸日日碰夜夜 | 亚洲三级免费看 | www.久久久久久久久久久久 | 亚洲精品在线91 | 精品在线一区 | 成人在线影视 | 午夜tv免费观看 | 久久精彩视频 | 少妇无套高潮一二三区 | av网站在线免费观看 |