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

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

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

本文轉載自公眾號“讀芯術”(ID:AI_Discovery)

[[324523]]

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

 

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

 

 

示例: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 

當您試圖訪問不存在的密鑰時會遇到什么情況?

  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)提示。

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

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

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

設置默認值

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

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

解決大小寫問題

假設您構建了Python字典,其中包含特定國家的人口數據。代碼將要求用戶輸入一個國家名并輸出顯示其人口數。

  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 

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

  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

 

一個簡單的解決方法:用小寫字母存儲所有國家/地區名稱。另外,將用戶輸入的所有內容轉換為小寫形式。

  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 

處理拼寫錯誤

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

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

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

循環將繼續運行,直到用戶進入exit。

優化方法

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

 

[[324526]]

 

 

圖源:unsplash

 

我找到了幾個適合解決key error的庫,其中我最喜歡的是標準的python庫:difflib。

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

1. # SequenceMatcher

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

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

讓我們使用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

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

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

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

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

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

 

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

 

 

圖源:unsplash

 

來看以下示例:

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

匯總

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

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

  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.

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

 

責任編輯:趙寧寧 來源: 今日頭條
相關推薦

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

數據庫工具技術

2017-06-30 13:23:59

SaaS供應商破產

2018-08-20 19:39:14

區塊鏈職業崗位

2021-02-22 17:13:47

HTTP1.1協議

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

重構代碼原代碼

2020-12-21 15:40:25

技術研發管理

2018-03-21 11:14:22

云計算云計算提供商數據

2017-07-04 15:07:44

Windows 7Windows數據錯誤

2020-06-23 14:24:05

2G網絡中國聯通用戶

2021-01-04 09:40:48

Linux運維Linux系統

2021-10-20 22:47:17

Windows 10Windows微軟

2018-06-11 15:20:24

點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 日本在线一二 | 国产精品亚洲片在线播放 | 免费日韩av网站 | 国产成人精品午夜 | 午夜国产羞羞视频免费网站 | 国产精品一区二区在线播放 | 成年人免费在线视频 | 羞羞视频免费在线 | 亚洲精品在线视频 | 亚洲精品久久久一区二区三区 | 国产亚洲一区二区三区 | 精品久久一区 | 国产一区久久 | 精品国产亚洲一区二区三区大结局 | 亚洲激情综合 | www.操com| 亚洲午夜久久久 | 中文在线视频观看 | 国产成人精品一区二区三区 | 91精品国产91久久久 | 麻豆av在线| 成年人的视频免费观看 | 欧美日韩一区二区三区四区五区 | 国产成人一区二 | 浴室洗澡偷拍一区二区 | 久久宗合色 | 欧美激情久久久久久 | 国产女人与拘做受视频 | 2022国产精品| 美女拍拍拍网站 | 精品一区二区三区四区外站 | 日韩av在线一区 | 国产japanhdxxxx麻豆 | 一区二区三区中文字幕 | 亚洲精品在线免费看 | 国产99久久久国产精品 | 日本亚洲欧美 | 91精品国模一区二区三区 | 欧美1区 | 日本久久综合 | 狠狠狠色丁香婷婷综合久久五月 |