Python大数据基础与实战范晖课后题答案.docx
- 文档编号:7124302
- 上传时间:2023-01-20
- 格式:DOCX
- 页数:16
- 大小:21.92KB
Python大数据基础与实战范晖课后题答案.docx
《Python大数据基础与实战范晖课后题答案.docx》由会员分享,可在线阅读,更多相关《Python大数据基础与实战范晖课后题答案.docx(16页珍藏版)》请在冰豆网上搜索。
Python大数据基础与实战范晖课后题答案
课后题答案
第1章
1.解释性、面向对象、动态数据类型、吉多·范罗苏姆
2.Python
3.包、模块、语句
4.B5.C
6.使用pip工具来安装扩展库,指令为:
pipinstall库文件名。
用pip命令管理Python扩展库需要在命令提示符环境中进行,并且需要切换至pip所在目录。
7.首先将.py源文件和python.exe文件关联,将.pyw源文件和pythonw.exe关联。
然后双击源文件即可执行。
8.常用的有三种方式,分别为
●import模块名[as别名]
●from模块名import对象名[as别名]
●frommathimport*
9.Python被称为人工智能的专用语言,Python下众多的开源框架对人工智能应用领域提
供了强大的支持,如计算机视觉库OpenCV、机器学习框架TensorFlow等。
借助于Django、web2py等框架,可以快速开发网站应用程序。
数据分析可以使用numpy、pandas、matplotlib、scipy等库。
第2章
1.Python采用的是基于值的内存管理方式,如果为不同变量赋值相同值,则在内存中只有一份该值,多个变量指向同一块内存地址id()
2.在Python中/表示普通除法(也叫真除法),结果是实数,而//表示整除,得到的结果是整数,并且自动向下取整。
3.
x=input('请输入3位以上的数字:
')
iflen(x)>=3:
x=int(x)
print('结果是:
',x//100)
else:
print('输入错误!
')
4.
x=input("inputanumber:
")
a,b,c=map(int,x)
print("resultis:
{0}\t{1}\t{2}".format(a,b,c))
5.sum()
6.True
7.19
8.False
9.(True,5)
10.True
11.5
12.5
13.1:
2:
3
14.
x=input("inputthreenumbers:
")
a,b,c=map(int,x.split())
print("sortedresultis:
",sorted((a,b,c)))
第3章
1.
importrandom
x=[random.randint(0,200)foriinrange(100)]
#第一种实现:
使用集合
s=set(x)
forvins:
print(v,':
',x.count(v))
#第二种实现:
使用字典
d=dict()
forvinx:
d[v]=d.get(v,0)+1
fork,vind.items():
print(k,v,sep=':
')
2.
x=input("inputalist:
")
x=eval(x)
p=input("inputtwopositon:
")
begin,end=map(int,p.split())
print(x[begin:
end+1])
3.[6foriinrange(10)]
4.
importrandom
x=[random.randint(0,100)foriinrange(20)]
print(x)
x[:
10]=sorted(x[:
10])
x[10:
]=sorted(x[10:
],reverse=True)
print(x)
5.[]
6.[18,19]
7.([1,3],[2])
8.当列表增加或删除元素时,列表对象自动进行内存扩展或收缩,从而保证元素之间没有缝隙,但这涉及到列表元素的移动,效率较低,应尽量从列表尾部进行元素的增加与删除操作以提高处理速度。
9.[1,2,3,1,2,3,1,2,3]
10.['1','2','3']
第4章
1.A2.D3.C4.D5.C
6.
name=input("请输入你的名字:
")
place=input("请输入你经常去的地方:
")
like=input("请输入你平时的爱好:
")
print('可爱的',name,',','最喜欢在',place,'地方进行',like)
或者:
test="可爱的{0},最喜欢在{1}地方进行{2}"
name=input("请输入你的名字:
")
place=input("请输入你经常去的地方:
")
like=input("请输入你平时的爱好:
")
v=test.format(name,place,like)
print(v)
7.
s=input("请输入一个待统计的字符串:
")
print(s.count(""))
第5章
1.Continue、break
2.while
3.C
4.B
5.Python提供了while和for两种循环控制结构,用来处理需要进行的重复操作,直到满足某些特定条件。
while循环一般用于循环次数难以提前确定的情况,也可以用于循环次数确定的情况。
for循环一般用于循环次数可以提前确定的情况,尤其适用于枚举或者遍历序列、迭代对象中元素的场合。
for循环写的代码通常更加清晰简单,因此编程时建议优先使用for循环。
相同或不同的循环结构之间可以相互嵌套,也可以和选择结构嵌套使用,用来实现更为复杂的逻辑。
6.
x=input('Pleaseinputaninteger:
')
x=int(x)
ifx%2==0:
print("{:
d}is偶数!
".format(x))
else:
print("{:
d}is奇数!
".format(x))
7.
x=input('Pleaseinputanintegerlessthan1000:
')
x=eval(x)
t=x
i=2
result=[]
whileTrue:
ift==1:
break
ift%i==0:
result.append(i)
t=t//i
else:
i+=1
print(x,'=','*'.join(map(str,result)))
第6章
1.
importmath
defIsPrime(v):
n=int(math.sqrt(v)+1)
foriinrange(2,n):
ifv%i==0:
return'No'
else:
return'Yes'
print(IsPrime(17))
print(IsPrime(30))
print(IsPrime(813))
2.
defdemo(v):
capital,little,digit,other=(0,)*4#或者capital=little=digit=other=0
foriinv:
if'A'<=i<='Z':
capital+=1
elif'a'<=i<='z':
little+=1
elif'0'<=i<='9':
digit+=1
else:
other+=1
return(capital,little,digit,other)
x='PEP498,formattedstringliterals.'
print(demo(x))
3.会。
defdemo():
a=3
print(a)
a=5
demo()
4.
defmySum(data):
sum=0
fordindata:
sum+=d
returnsum
5.
defmySorted(lst,reverse=False):
lst=lst[:
]
length=len(lst)
foriinrange(0,length-1):
forjinrange(i+1,length):
#比较相邻两个元素大小,并根据需要进行交换
#默认升序排序
exp='lst[i]>lst[j]'
#如果reverse=True则降序排序
ifreverse:
exp='lst[i] ifeval(exp): lst[i],lst[j]=lst[j],lst[i] returnlst 6.-2 7. defdemo(*v): print(max(v)) print(sum(v)) 8.deff(n): a=b=c=1 foriinrange(n-3): c,b,a=a+b+c,c,b returnc 第7章 1.B2.C3.D4.C5.A 6. classStudent: #学生类 count=0#计数 def__init__(self,name,age): self.name=name self.age=age Student.count+=1#要使得变量全局有效,就定义为类的属性 deflearn(self): print("islearning") stu1=Student("jack",33) stu2=Student("amy",24) stu3=Student("lucy",22) stu4=Student("lulu",45) print("实例化了%s个学生"%Student.count) 7. classB: def__init__(self): pass defhandle(self): print("B.handle") classA(B): def__init__(self): super().__init__() defhandle(self): super().handle()#super依赖于继承 a=A() a.handle() 第8章 1.C2.A3.D4.B5.A 6. try: score=int(input("请输入学生的成绩: ")) ifscore>=90andscore<=100: print("A: 优秀") elifscore>=80andscore<90: print("B: 良好") elifscore>=60andscore<80: print("C: 合格") else: assertscore>60,"D: 不及格" exceptExceptionasresult: print("低于60分: \n",result) 7. classmy_error(Exception): def__init__(self,stri): self.leng=len(stri) defprocess(self): ifself.leng<5: return'Theinputisoflength%s,expectingatleast5'%self.leng else: return'printsuccess' try: s=input("请输入字符串: ") raisemy_error(s) exceptmy_errorase: print(e.process()) 第9章 1.C2.D3.D4.A5.B 6. oldFileName=input("请输入要拷贝的文件名字: ") oldFile=open(oldFileName,'r') ifoldFile: #提取文件的后缀 fileFlagNum=oldFileName.rfind('.') iffileFlagNum>0: fileFlag=oldFileName[fileFlagNum: ] #组织新的文件名 newFileName=oldFileName[: fileFlagNum]+'[复件]'+fileFlag #创建新文件 newFile=open(newFileName,'w') #把旧文件中的数据复制到新文件中 forlineContentinoldFile.readlines(): newFile.write(lineContent) #关闭文件 oldFile.close() newFile.close() 7. importos importsys sys.setrecursionlimit(1000)#setthemaximumdepthas1500 file_path=input('请输入待查找的目录: ') file_name=input('请输入待查找的文件: ') deffile_find(file_path,file_name): ifos.path.isdir(file_path): #os.chdir(file_path)#进入当前路径 ile_list=os.listdir(file_path) foreachinfile_list: temp_dir=file_path+os.sep+each ifos.path.isdir(temp_dir): #开始递归进入下一级子目录 temp=file_find(temp_dir,file_name) iftemp==True: returnTrue elifos.path.isfile(temp_dir)andeach==file_name: returnTrue #os.chdir('..')#没找到文件,退回上一个目录 returnFalse else: print('{}不是一个目录'.format(file_path)) file_path='D: \PythonTest\book1' file_name='1.txt' print(file_find(file_path,file_name)) 第10章 1.B2.C3.A4.D5.C 6. (1) %matplotlibinline importmatplotlib.pyplotasplt importseabornassns iris=sns.load_dataset("iris") sns.set(style="ticks") fig,axes=plt.subplots(1,2,figsize=(20,5)) sns.swarmplot(x='petal_length',y="petal_width",ax=axes[0],data=iris,hue="species") sns.swarmplot(x='sepal_length',y="sepal_width",ax=axes[1],data=iris,hue="species") plt.show() (2) sns.lmplot("petal_length","petal_width",hue="species",markers=["x","o","s"],data=iris) plt.show() 从回归图上可以看出这两个特征之间是线性相关的。 第11章 1.B、C 2.D 3.C 4.C 5. importnumpyasnp arr=np.random.rand(10,5) 6. importnumpyasnp matr1=np.arange(1,5).reshape(2,2) matr2=np.arange(5,9).reshape(2,2) matr1*matr2 7.v=np.array([1,-1,1]).reshape(3,1).T P=(v*v.T)/(v.T*v) Q=np.eye(3,3)-P 8.dir(np);np.arange? 9.np.array([[1,-1,0]])生成一个(1,3)的矩阵,np.array([1,-1,0])生成一个向量。 第12章 1.A2.D3.D4.A5.B6.B 7. (1) importseabornassns mpg=sns.load_dataset("mpg") mpg.ndim mpg.size (2) mpg.describe() (3) mpg.groupby('cylinders')['mpg','horsepower'].agg("mean") mpg.groupby('origin')['mpg','horsepower'].agg("mean") 第13章 1. fromlxmlimportetree importrequests response=requests.get(" response.encoding="utf-8" selector=etree.HTML(response.text) news_text=selector.xpath('//*[@id="u1"]/a[1]/text()')[0] news_url=selector.xpath('//*[@id="u1"]/a[1]/@href')[0] 2. 1)创建scrapy项目 scrapystartprojectsdWeatherSpider 2)创建爬虫程序 scrapygenspidereveryCitySD 3)使用浏览器打开网址 4)在页面上单击鼠标右键,选择“查看网页源代码”,找到与“城市预报列表”对应的位置。 选择并打开陕西省内任意城市的天气预报页面,以西安为例。 选择“查看页面源代码”,找到与天气预报相对应的位置。 5)修改items.py文件,定义要爬虫的内容 importscrapy classSdweatherspiderItem(scrapy.Item): city=scrapy.Field() weather=scrapy.Field() 6)修改爬虫文件everyCitySD.py #-*-coding: utf-8-*- importscrapy fromreimportfindall importrequests fromsdWeatherSpider.itemsimportSdweatherspiderItem classEverycitysdSpider(scrapy.Spider): allowed_domains=[''] name='everyCitySD' allowed_domains=[''] start_urls=[' url=r' response=requests.get(url) response.encoding="utf-8" contents=response.text pattern=' "href="(.+? )"target="_blank">.+? ' forurlinfindall(pattern,contents): #获取地市级预报的网页地址 start_urls.append(url) defparse(self,response): item=SdweatherspiderItem() city=response.xpath('//div[@class="crumbsfl"]//a[2]//text()').extract()[0] item['city']=city selector=response.xpath('//ul[@class="tclearfix"]')[0] weather='' forliinselector.xpath('./li'): date=li.xpath('./h1//text()').extract()[0] cloud=li.xpath('./p[@title]//text()').extract()[0] high=li.xpath('./p[@class="tem"]//span//text()').extract()[0] low=li.xpath('./p[@class="tem"]//i//text()').extract()[0] wind=li.xpath('./p[@class="win"]//em//span[1]/@title').extract()[0] wind=wind+li.xpath('./p[@class="win"]//i//text()').extract()[0] weather=weather+date+': '+cloud+','+high+'/'+low+','+wind+'\n' item['weather']=weather return[item] 7)修改pipelines.py文件,把爬取的数据写入文件weather.csv importcsv classSdweatherspiderPipeline(object): defprocess_item(self,item,spider):
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Python 数据 基础 实战 课后 答案