下载安卓APP箭头
箭头给我发消息

客服QQ:3315713922

编程语言用户输入错误了怎么办?

作者:读芯术     来源: 今日头条点击数:1604发布时间: 2020-05-03 16:37:47

标签: 编程语言Python安全

大神带你学编程,欢迎选课

用户失误我“买单”:用户输入错误了怎么办?在过去的几十年间,大量的编程语言被发明、被取代、被修改或组合在一起。尽管人们多次试图创造一种通用的程序设计语言,却没有一次尝试是成功的。之所以有那么多种不同的编程语言存在的原因是,编写程序的初衷其实也各不相同;新手与老手之间技术的差距非常大,而且有许多语言对新手来说太难学;还有,不同程序之间的运行成本(runtime cost)各不相同。

本文将为你提供几种处理Python字典 keyerror的方法。去努力构建一个python智能字典,它能帮你处理用户的输入错误问题。

编程语言用户输入错误了怎么办?_编程语言_Javascript_安全_课课家

问题来源于生活。上周在做业余项目时,我遇到了一个非常有趣的设计问题:“如果用户输入错误了怎么办?”如果输入错误,就会发生以下这种情况:

示例: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’不是字典中的键,因此会收到错误提示。

图源: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搜索)。

图源: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智能字典的构建方法,你学会了吗?

 编程语言往往使程序员能够比使用机器语言更准确地表达他们所想表达的目的。对那些从事计算机科学的人来说,懂得程序设计语言是十分重要的,因为在当今所有的计算都需要程序设计语言才能完成。

赞(15)
踩(0)
分享到:
华为认证网络工程师 HCIE直播课视频教程