10-11 喜欢的数字:编写一个程序,提示用户输入他喜欢的数字,并使用json.dump()将这个数字存储到文件中。在编写一个程序,从文件中读取这个值,并打印消息“I know your favourite number! It’s ____. ”
filenames = ['alice.txt', 'abc.txt', 'little_women.txt', 'moby_dick.txt']
for filename in filenames:
try:
with open(filename,encoding='UTF-8') as file_object:
contents = file_object.read()
except FileNotFoundError:
print("The file " + filename + " is not exists!")
else:
counts = contents.count('the')
print("I know your favourite number! It's " + str(counts) + ".")
10-12 记住喜欢的数字:将上题的两个程序合二为一。如果存储了用户喜欢的数字,就像用户显示它,否则提示用户输入他喜欢的数字并将其存储到文件中。运行这个程序两次,看看它是否像预期的那样工作。
import json
def f_number():
filename = 'favourite_number.json'
try:
with open(filename) as file_object:
number = json.load(file_object)
except FileNotFoundError:
with open(filename, 'w') as file_object:
number = input("Enter your favourite number: ")
json.dump(number, file_object)
else:
print("Your favourite number is: " + number)
f_number()
10_13 验证用户:最后一个remember_me.py版本假设用户要么已输入其用户名,要么是首次运行该程序。我们应修改这个程序,以应对这样的情形:当前和最后一次运行该程序的用户并非同一个人。
为此,在greet_user()中打印欢迎用户回来的消息前,先询问他用户名是否是对的。如果不对,就调用get_new_username()让用户输入正确的用户名。
import json
def get_new_username():
username = input("Enter your correct name: ")
return username
def get_sorted_username():
"""如果用户存储了用户名就获取它"""
filename = 'username.json'
try:
with open(filename) as file_object:
username = json.load(file_object)
except FileNotFoundError:
return None
else:
return username
def greet_user():
"""问候用户,并指出其名字"""
username = get_sorted_username()
yourname = input("Enter your name: ")
if username == yourname:
print("Welcome back, " + username + "!")
else:
username = get_new_username()
filename = 'username.json'
with open(filename, 'w') as file_object:
json.dump(username, file_object)
print("We'll remember you when you come back, " + username + "!")
greet_user()