当前位置:   article > 正文

Python.习题六 字典与集合(下)_编写程序,对用户输入的英文字符串

编写程序,对用户输入的英文字符串

Python.<习题六> 字典与集合

11.编写程序,对用户输入的英文字符串中各字母出现的次数进行统计(不区分大写字母和小写字母),统计结果使用字典存放。例如,字符串"I have 2 ideas."的统计结果为{“i”:2,“h”:1,“a”:2,“v”:1,“e”:2,“d”:1,“s”:1}。假设用户输入的字符串中可能包含字母以外的其他字符。

s=input("请输入字符串:")
myDict={
   }
for c in s:
    ch=c.lower()
    if ch.isalpha():
        myDict [ch]= myDict.get(ch,0)+1
print(myDict) 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

在这里插入图片描述
12.已知字符串变量s=“When in the course of human events,it becomes necessary for one people to dissolve the political bands which have connected them with another,and to assume among the powers of the earth,the separate and equal atation to which the Laws of Nature and of Nature’s God entitle them,a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.”,存放了美国独立宣言中的一段话。试编写程序,实现以下功能:
(1)对文本中每个单词出现的次数进行统计,并将结果输出。
(2)输出出现次数排在前五名的单词。

s='''When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the Powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.'''
s=s.lower().replace(',','').replace('.','')
lst=s.split(' ')
dic={
   }
for word in lst:
    dic[word]=dic.get(word,0)+1
print(dic)
newlst=[(v,k) for k,v in dic.items()]
newlst.sort()
print(newlst[-1:-6:-1])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

在这里插入图片描述
13.编写程序,使用嵌套字典描述表中内容之间的映射关系,输出字典中每种颜色的事物数目,如紫色的食物有三个。
在这里插入图片描述

dic_menu={
   "蔬菜":{
   "青菜":"绿色","胡萝卜":"橙色","茄子":"紫色","毛豆":"绿色"},
          "水果":{
   "山竹":"紫色","香蕉":"黄色","橙子":"橙色","草莓":"红色"},
          "饮料":{
   "椰子汁":"白色","西瓜汁":"红色","玉米汁":</
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/494481
推荐阅读
相关标签
  

闽ICP备14008679号