10-1 Python学习笔记 在文本编辑器中新建一个文件 写几句话来总结一下你至此学到的Python知识 其中每一行都以“In Python you can”打头。将这个文件命名为learning_python.txt 并存储到为完成本章练习而编写的程序所在的目录中。编写一个程序 它读取这个文件 并将你所写的内容打印三次 第一次打印时读取整个文件 第二次打印时遍历文件对象 第三次打印时将各行存储在一个列表中 再在with代码块外打印它们。
# 第一次打印时读取整个文件 with open( learning_python.txt ) as f: print(f.read()) # 第二次打印时遍历文件对象 with open( learning_python.txt ) as f: for line in f: print(line.rstrip()) # 第三次打印时将各行存储在一个列表中 再在with代码块外打印它们 with open( learning_python.txt ) as f: lines f.readlines() for line in lines: print(line.rstrip()) f.close()
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 f: contents f.read() print(contents.replace( Python , C )) f.close()
10-3 访客 编写一个程序 提示用户输入名字。用户做出响应后 将其名字写入文件guest.txt中。
filename guest.txt name input( 请输入您的名字 ) with open(filename, w ,encoding utf-8 ) as f: print(f.write(name)) f.close()
10-4 访客名单 编写一个while 循环 提示用户输入名字。用户输入名字后 在屏幕上打印一句问候语 并将一条到访记录添加到文件guest_book.txt中。确保这个文件中的每条记录都独占一行。
filename guest.txt
while True:
name input( 请输入您的名字 )
msg print(f 欢迎{name}访问n )
with open(filename, w ,encoding utf-8 ) as f:
print(f.write(msg))
f.close()
10-5 调查 编写一个while 循环 询问用户为何喜欢编程。每当用户输入一个原因后 都将其添加到一个存储所有原因的文件中。
filename guest.txt while True: problem input( 请回答 您为何喜欢编程 ) with open(filename, w ,encoding utf-8 ) as f: print(f.write(problem)) f.close()
10-6 加法运算 提示用户提供数值输入时 常出现的一个问题是 用户提供的是文本而不是数。在此情况下 当你尝试将输入转换为整数时 将引发ValueError 异常。编写一个程序 提示用户输入两个数 再将其相加并打印结果。在用户输入的任何一个值不是数时都捕获ValueError 异常 并打印一条友好的错误消息。对你编写的程序进行测试 先输入两个数 再输入一些文本而不是数。
num1 input( 请输入第一个数 ) num2 input( 请输入第二个数 ) print(int(num1) int(num2)) except ValueError: print( 您输入的不是数 )
10-7 加法计算器 将为完成练习10-6而编写的代码放在一个while 循环中 让用户犯错 输入的是文本而不是数 后能够继续输入数。
while True: num1 input( 请输入第一个数 ) um2 input( 请输入第二个数 ) try: print(int(num1) int(num2)) break except ValueError: print( 您输入的不是数 )
10-8 猫和狗 创建文件cats.txt和dogs.txt,在第一个文件中至少存储三只猫的名字 在第二个文件中至少存储三条狗的名字。编写一个程序 尝试读取这些文件 并将其内容打印到屏幕上。将这些代码放在一个try-except代码块中 以便在文件不存在时捕获FileNotFound错误 并显示一条友好的消息。将任意一个文件移到另一个地方 并确认except 代码块中的代码将正确执行。
filenames [ cats.txt , dogs.txt ] for i in filenames: try: with open(i,encoding utf-8 ) as f: contents f.read() print(contents) except FileNotFoundError: print( 文件不存在 )
10-9 静默的猫和狗 修改你在练习10-8中编写的except代码块 让程序在任意文件不存在时静默失败。
filenames [ cats.txt , dogs.txt ] for i in filenames: try: with open(i,encoding utf-8 ) as f: contents f.read() print(contents) except FileNotFoundError: pass
Jenny A Village Idy1.txt
The July day was sinking into evening, an evening light that was soft and mellow in spite of the line of stormcloud above the cathedral. It was the first bright day that had been known for many weeks, and all available hands had been turned to work upon the hay which, green and damp still from recent experiences, was lying spread or in haycocks on the ground. Here and there, on soil close to the river’s brink, the masses of purple loosestrife made a glow of colour; or in some uncut field where the grass was short and brown the dark red cows were pasturing quietly; or now and then one, unconsciously[2] picturesque, would be standing on the bank of the river, a distinct picture there. The train steamed onwards with its scanty freight of passengers, between the lines of the river and the canal, in the midst of the quiet fields and the mellow evening light.
10-10 常见单词 访问古登堡计划 找一些你想分析的图书。下载这些作品的文本文件或将浏览器中的原始文本复制到文本文件中。可以使用方法count()来确定特定的单词或短语在字符串中出现了多少次。例如 下面的代码计算’row’在一个字符串中出现了多少次
line “Row, row, row your boat”
line.count(‘row’)
2
line.lower().count(‘row’)
3
请注意 通过使用lower() 将字符串转换为小写 可捕捉要查找单词的所有格式 而不管其大小写如何。编写一个程序 它读取你在古登堡计划中获取的文件 并计算单词’the’ 在每个文件中分别出现了多少次。这里计算得到的结果并不准确 因为将诸如’then’ 和’there’ 等单词也计算在内了。请尝试计算’the 包含空格 出现的次数 看看结果相差多少。
the_obj 0
book Jenny A Village Idy1.txt
with open(book,encoding utf-8 ) as f:
lines f.readlines()
for line in lines:
content line.lower().count( the )
the_obj content
print(f the 出现{the_obj}次 )
10-11 喜欢的数 编写一个程序 提示用户输入喜欢的数 并使用json.dump() 将这个数存储到文件中。再编写一个程序 从文件中读取这个值 并打印如下所示的消息。
#I know your favorite number! It’s _____.
import json
number input( 请输入喜欢的数 )
filename 10.11.json
with open( 10.11.json , w ,encoding utf-8 ) as f:
json.dump(number,f)
with open( 10.11.json ,encoding utf-8 ) as f:
content json.load(f)
print(f I know your favorite number! It s{content} )
10-12 记住喜欢的数 将练习10-11中的程序合二为一。如果存储了用户喜欢的数 就向用户显示它 否则提示用户输入喜欢的数并将其存储到文件中。运行这个程序两次 看看它能否像预期的那样工作。
import json
filename 10.11.json
with open(filename) as f:
num json.load(f)
except FileNotFoundError:
num input( 请输入喜欢的数 )
with open(filename, w ,encoding utf-8 ) as f:
json.dump(num,f)
print(f We ll remember the number of {num} )
else:
print(f There is your favorite number:{num} )
username.json
{ username : Eric }
10-13 验证用户 最后一个remember_me.py版本假设用户要么已输入用户名 要么是首次运行该程序。我们应该修改这个程序 以防当前用户并非上次运行该程序的用户。为此 在greet_user() 中打印欢迎用户回来的消息前 询问他用户名是否正确。如果不对 就调用get_new_username()让用户输入正确的用户名。
import json
def get_stored_username():
如果存储了用户名 就获取它。
filename username.json
try:
with open(filename) as f:
username json.load(f)
except FileNotFoundError:
return None
else:
return username
def get_new_username():
提示用户输入用户名。
username input( What is your name? )
filename username.json
with open(filename, w ) as f:
json.dump(username, f)
return username
def greet_user():
问候用户 并指出其名字。
username get_stored_username()
print(f 您的用户名是否为 {username} )
user input( 正确请输入Y 错误请输入N )
if user Y :
print(f Welcome back, {username}! )
else:
username get_new_username()
print(f 您的正确用户名是 {username}! )
greet_user()



