Python计算机视觉编程与应用 习题及答案 第2章 习题答案.docx

Python计算机视觉编程与应用 习题及答案 第2章 习题答案.docx

  1. 1、本文档共2页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多

第2章Python文件操作与异常处理

习题答案

2-1.创建文件data.txt,共100000行,每行存放一个1~100之间的整数

importrandom

withopen(data.txt,w)asf:

for_inrange(100000):

f.write(str(random.randint(1,100))+\n)

2-2生成大文件ips.txt并统计频率

importrandom

importipaddress

withopen(ips.txt,w)asf:

for_inrange(1200):

net=ipaddress.ip_network(172.25.254.0/24)

ip=str(random.choice(list(net.hosts())))

f.write(ip+\n)

fromcollectionsimportCounter

withopen(ips.txt,r)asf:

ip_counts=Counter(f.read().splitlines())

forip,countinip_counts.most_common(10):

print(f{ip}:{count})

2-3定义函数func(filename)

deffunc(filename):

try:

withopen(filename,r)asf:

content=f.read()

returncontent#确保这个return在try块内部

exceptExceptionase:

print(fAnerroroccurred:{e})

returnNone#同样,这个return也在try块之外,但属于except块

#示例使用

content=func(data.txt)

ifcontent:

print(content[:100]+...)

else:

print(Nocontentorerror.)

2-4自定义异常类并捕获异常

classShortInputException(Exception):

def__init__(self,length,message=Inputtooshort):

self.length=length

self.message=f{message}.Theinputisoflength{self.length},expectingatleast5.

super().__init__(self.message)

try:

user_input=input(Enterastring:)

iflen(user_input)5:

raiseShortInputException(len(user_input))

else:

print(Success)

exceptShortInputExceptionase:

print(e)

exceptExceptionase:

print(fAnunexpectederroroccurred:{e})

您可能关注的文档

文档评论(0)

xiaobao + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档