Chapter10/11(文件和异常/测试代码)

#10-1 Python学习笔记 :在文本编辑器中新建一个文件,写几句话来总结一下你至此学到的Python知识,其中每一行都以“In Python you can”打头。
# 将这个文件命名为learning_python.txt,并将其存储到为完成本章练习而编写的程序所在的目录中。编写一个程序,它读取这个文件,
# 并将你所写的内容打印三次:第一次打印时读取整个文件;第二次打印时遍历文件对象;第三次打印时将各行存储在一个列表中,再在with 代码块外打印它们。
####读取整个文件####
with open('learning_python.txt') as file_object:
    contents=file_object.read()
    print(contents)
print("--------------------------")
#####遍历文件对象#####
with open('learning_python.txt') as file_object:
    for content in file_object:
        print(content.strip())
print("--------------------------")
#####将各行存储在一个列表中#####
with open('learning_python.txt') as file_object:
    lines=file_object.readlines()
    for line in lines:
        print(line.strip())
#结果
In Python you can learn English
In Python you can grab data
In Python you can build web
--------------------------
In Python you can learn English
In Python you can grab data
In Python you can build web
--------------------------
In Python you can learn English
In Python you can grab data
In Python you can build web
#10-2 C语言学习笔记 :可使用方法replace() 将字符串中的特定单词都替换为另一个单词。下面是一个简单的示例,
# 演示了如何将句子中的'dog' 替换为'cat' :
# >>> message = "I really like dogs."
# >>> message.replace('dog', 'cat')
#'I really like cats.'
# 读取你刚创建的文件learning_python.txt中的每一行,将其中的Python都替换为另一门语言的名称,如C。将修改后的各行都打印到屏幕上。
with open('learning_python.txt') as file_object:
    lines=file_object.readlines()
    for line in lines:
        line=line.replace('Python','C')
        print(line.strip())
#结果
In C you can learn English
In C you can grab data
In C you can build web
#10-3 访客 :编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写入到文件guest.txt
names=input("Enter your name: ")
with open('guest.txt','w') as file_object:
    file_object.write(names)
#结果
Enter your name: haly
############guest.txt###########
haly
# 10-4 访客名单 :编写一个while 循环,提示用户输入其名字。用户输入其名字后,在屏幕上打印一句问候语,
# 并将一条访问记录添加到文件guest_book.txt中。确保这个文件中的每条记录都独占一行。
while True:
    names = input("Enter your name: ")
    print("How are you, "+names)
    with open('guest.txt', 'a') as file_object:
        file_object.write(names+'\n')
#结果
Enter your name: Helen
How are you, Helen
Enter your name: Angela
How are you, Angela
Enter your name: 
############guest.txt###########
haly
Helen
Angela
#10-5 关于编程的调查 :编写一个while 循环,询问用户为何喜欢编程。
# 每当用户输入一个原因后,都将其添加到一个存储所有原因的文件中。
while True:
    reason = input("Why you so like programming? ")
    with open('reasons.txt', 'a') as file_object:
        file_object.write(reason+'\n')
#结果
Why you so like programming? Becaunse I love it
Becaunse I love it
Why you so like programming? No reason
No reason
Why you so like programming? Just to play
Just to play
Why you so like programming? 
############reasons.txt###########
Becaunse I love it
No reason
Just to play

依赖于try代码块成功执行的代码都应放到else代码块中

Python有一个pass 语句,可在except 代码块中使用它来让Python 什么都不要做

#10-6 加法运算:提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数字。在这种情况下,当你尝试将输入转换为整数时,
# 将引发ValueError异常。编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的任何一个值不是数字时都捕获TypeError 异常,
#并打印一条友好的错误消息。对你编写的程序进行测试:先输入两个数字,再输入一些文本而不是数字.
while True:
    """加法运算 """
    try:
        num1 = int(input("Enter first number: "))
        num2 = int(input("Enter second number: "))
        sum = num1 + num2
    except ValueError:
        print("please enter numbers rather than words")
    else:
        print("the sum is "+str(sum))

#结果
Enter first number: 5
Enter second number: 7
the sum is 12
Enter first number: 8
Enter second number: lalaland
please enter numbers rather than words
Enter first number: 
#10-8 猫和狗 :创建两个文件cats.txt和dogs.txt,在第一个文件中至少存储三只猫的名字,在第二个文件中至少存储三条狗的名字。
# 编写一个程序,尝试读取这些文件,并将其内容打印到屏幕上。将这些代码放在一个try-except 代码块中,以便在文件不存在时捕获FileNotFound 错误,
# 并打印一条友好的消息。将其中一个文件移到另一个地方,并确认except 代码块中的代码将正确地执行。
def readfile(filename):
	"""读取文件"""
	try:
		with open(filename) as file_object:
			contents=file_object.read()
	except FileNotFoundError:
		print("the file doesn't exits")
	else:
			print("the cats include:\n"+contents)
readfile("cats")
readfile("dogs")
#结果
the cats include:
HelloKitty
JiaFei
BuOu
the cats include:
WangCai
XiaoHey
XiaoHuang
#10-9 沉默的猫和狗 :修改你在练习10-8中编写的except 代码块,让程序在文件不存在时一言不发。
def readfile(filename):
	"""读取文件"""
	try:
		with open(filename) as file_object:
			contents=file_object.read()
	except FileNotFoundError:
		pass
	else:
			print("the cats include:\n"+contents)
readfile("cats")
readfile("birds")
readfile("dogs")
readfile("fishes")
#结果
the cats include:
HelloKitty
JiaFei
BuOu
the cats include:
WangCai
XiaoHey
XiaoHuang
# 10-10 常见单词:访问项目Gutenberg(http://gutenberg.org/ ),并找一些你想分析的图书。
# 下载这些作品的文本文件或将浏览器中的原始文本复制到文本文件中。
# 你可以使用方法count() 来确定特定的单词或短语在字符串中出现了多少次。
# 例如,下面的代码计算'row'在一个字符串中出现了多少次:
# >>> line = "Row, row, row your boat"
# >>> line.count('row')
# 2
# >>> line.lower().count('row')
# 3
with open("paper") as file_object:
	contents=file_object.read()
print(contents.count("it"))
print(contents.lower().count("it"))
#结果
6
7
#10-11 喜欢的数字:编写一个程序,提示用户输入他喜欢的数字,并使用json.dump() 将这个数字存储到文件中。
#再编写一个程序,从文件中读取这个值,并打印消息“I knowyour favorite number! It's _____.”。
####first_json####
import json
filename = 'number.json'
number=input("please enter your favorite number: ")
with open(filename,'w') as f_obj:
	json.dump(number,f_obj)
####second_json####
import json
filename = 'number.json'
with open(filename) as f_obj:
	numbers=json.load(f_obj)
	print("I know your favorite number! It's "+numbers)
#结果

####first_json####
please enter your favorite number: 8
####second_json####
I know your favorite number! It's 8
#10-12 记住喜欢的数字 :将练习10-11中的两个程序合而为一。如果存储了用户喜欢的数字,就向用户显示它,
# 否则提示用户输入他喜欢的数字并将其存储到文件中。运行这个程序两次,看看它是否像预期的那样工作
import json
filename = 'number.json'
try:
	with open(filename) as f_obj:
		number=json.load(f_obj)
except FileNotFoundError:
	number=input("please enter your favorite number: ")
	with open(filename,'w') as f_obj:
		json.dump(number,f_obj)
else:
	print("I know your favorite number! It's "+number)
#结果
I know your favorite number! It's 8
#10-13 验证用户 :最后一个remember_me.py版本假设用户要么已输入其用户名,要么是首次运行该程序。
# 我们应修改这个程序,以应对这样的情形:当前和最后一次运行该程序的用户并非同一个人。
# 为此,在greet_user() 中打印欢迎用户回来的消息前,先询问他用户名是否是对的。如果不对,就调用get_new_username() 让用户输入正确的用户名。
import json
def get_stored_username():
	"""如果存储了用户名,就获取它"""
	filename = 'usernames.json'
	try:
		with open(filename) as f_obj:
			username = json.load(f_obj)
	except FileNotFoundError:
		return None
	else:
		return username
def get_new_username():
	"""提示用户输入用户名"""
	username = input("What is your name? ")
	filename = 'usernames.json'
	with open(filename, 'w') as f_obj:
		json.dump(username, f_obj)
	return username
def greet_user():
	"""问候用户,并指出其名字"""
	username = get_stored_username()
	if username:
		answer = input("is your name "+username+" right? "+"  response:(yes or no)")
		if answer=='yes':
			print("Welcome back, " + username + "!")
		else:
			newname=get_new_username()
			print("We'll remember you when you come back, " + newname + "!")
	else:
		username = get_new_username()
		print("We'll remember you when you come back, " + username + "!")
greet_user()
#结果
What is your name? Selina
We'll remember you when you come back, Selina!
--------------------------------------------------
is your name selina right?   response:(yes or no)yes
Welcome back, selina!
--------------------------------------------------
is your name selina right?   response:(yes or no)  no
What is your name? helen
We'll remember you when you come back, helen!

方法名必须以test_打头,这样它才会在继承于unittest.TestCase的类中自动运行

#11-1 城市和国家 :编写一个函数,它接受两个形参:一个城市名和一个国家名。这个函数返回一个格式为City, Country 的字符串,如Santiago, Chile 。
# 将这个函数存储在一个名为city_functions.py的模块中。创建一个名为test_cities.py的程序,对刚编写的函数进行测试
# (别忘了,你需要导入模块unittest 以及要测试的函数)。编写一个名为test_city_country() 的方法,
# 核实使用类似于'santiago' 和'chile' 这样的值来调用前述函数时,得到的字符串是正确的。运行test_cities.py ,确认测试test_city_country() 通过了。
##############city_functions.py##################
def city_country(City,Country):
	return City.title()+","+Country.title()
##############test_cities.py的程序################
import unittest
from printing_functions import city_country
class NameTestCase(unittest.TestCase):
    """测试printing_functions.py"""
def test_city_country(self):
    formatted_name=city_country('shanghai','china')
    self.assertEqual(formatted_name,'Shanghai,China')
unittest.main()

#结果
.
----------------------------------------------------------------------
Ran 1 tests in 0.001s

OK
#11-2 人口数量 :修改前面的函数,使其包含第三个必不可少的形参population ,并返回一个格式为City, Country - population xxx 的字符串,
# 如Santiago, Chile - population 5000000 。运行test_cities.py,确认测试test_city_country() 未通过。
# 修改上述函数,将形参population 设置为可选的。再次运行test_cities.py,确认测试test_city_country() 又通过了。
# 再编写一个名为test_city_country_population() 的测试,核实可以使用类似于'santiago' 、'chile' 和'population=5000000' 这样的值来调用这个函数。
# 再次运行test_cities.py,确认测试test_city_country_population() 通过了.
##############city_functions.py#############
def city_country(city,country,population=''):
	if population:
		return city.title() + "," + country.title() + " - population " + population
	else:
		return city.title()+","+country.title()
##############tesy_city.py##################
import unittest
from printing_functions import city_country
class NameTestCase(unittest.TestCase):
    """测试printing_functions.py"""
    def test_city_country(self):
        formatted_name=city_country('shanghai','china')
        self.assertEqual(formatted_name,'Shanghai,China')
    def test_city_country_population(self):
        formatted_name = city_country('Tokyo', 'Japan','500million')
        self.assertEqual(formatted_name, 'Tokyo,Japan - population 500million')
unittest.main()
#结果
..
----------------------------------------------------------------------
Ran 2 tests in 0.001s

OK
#11-3 雇员:编写一个名为Employee 的类,其方法__init__() 接受名、姓和年薪,并将它们都存储在属性中。
# 编写一个名为give_raise() 的方法,它默认将年薪增加5000美元,但也能够接受其他的年薪增加量。
# 为Employee 编写一个测试用例,其中包含两个测试方法:test_give_default_raise() 和test_give_custom_raise() 。使用方法setUp() ,以免在
# 每个测试方法中都创建新的雇员实例。运行这个测试用例,确认两个测试都通过了
class Employee():
    def __init__(self,first,last,salary):
        self.first=first
        self.last=last
        self.salary=salary
    def give_raise(self,add=5000):
        self.salary+=add
        return self.salary
import unittest
class NameTestCase(unittest.TestCase):
    def setUp(self):
        self.employee=Employee("Helen","Wang",6000)
    def test_give_default_raise(self):
        sala=str(self.employee.give_raise())
        self.assertEqual(sala, '11000')
    def test_give_custom_raise(self):
        sal=str(self.employee.give_raise(2000))
        self.assertEqual(sal,'8000')
unittest.main()
#结果
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值