#10-6加法运算
num1=input("Please enter a number: ")
num2=input("Please enter another number: ")
#try:可能引发异常的代码
try:
sum=int(num1)+int(num2)
#except:引发指定异常如何处理
except ValueError:
print("You should enter numbers not string.")
#else:try代码块成功运行时,运行的代码
else:
print(sum)
#10-7加法运算器
'''对两个数求和,输入即使不是数字为文本,也可继续运行'''
print("Give me two numbers, and I'll add them.")
print("Enter 'q' to quit")
while True:
num1=input("Please enter a number: ")
num2=input("Please enter another number: ")
if num1=='q' or num2=='q':
break
#else:
try:
sum=int(num1)+int(num2)
except ValueError:
pass
else:
print(sum)
#10-8猫与狗
'''读取cats.txt与dogs.txt文件内存储的名称'''
names=['cats.txt','dogs.txt']
for name in names:
filename=name
try:
with open(filename) as f_obj:
lines=f_obj.readlines()
#倘若任一文件不存在,输出友好的错误信息
except FileNotFoundError:
print(filename + " file is not found.")
else:
for line in lines:
print(line + '\n')
Notes:无try-except-else语句时,else代码块内for语句与try代码块内lines语句是同缩进的;使用try-except-else语句后,依照其本身处理意义,不是同缩进也无妨。
#10.3.6-7分析文本
def count_words(filename):
'''计算一个文件中包含多少个单词'''
try:
with open(filename,encoding='gb18030',errors='ignore') as f_obj:
contents=f_obj.read()
except FileNotFoundError:
msg="Sorry, the file " + filename + " does not exist."
print(msg)
#出现FileNotFoundError异常时,执行except代码块,什么都不会发生
#pass
else:
#计算文件中包含多少个单词
words=contents.split()
num_words=len(words)
print("The file " + filename + " has about " + str(num_words) + " words")
filenames=['Alice’s_Adventures_in_Wonderland.txt','Japanese Girls and Women by Alice Mabel Bacon']
for filename in filenames:
count_words(filename)
Notes:encoding方式可以为utf-8,gbk等,无需修改txt文件格式,只要在open函数内指定编码方式;errors:有些字符无法读取,进行忽略处理。
#10-10 特定的单词或短语在字符串中出现多少次
filename='Alice’s_Adventures_in_Wonderland.txt'
with open(filename,encoding='gb18030',errors='ignore') as f_obj:
contents=f_obj.read()
num1=contents.count('the')
print(num1)
num2=contents.lower().count('the')
print(num2)
#10-10 特定的单词或短语在字符串中出现多少次——改良版
def count_words(filename,word):
'''定义一个函数,查找文件中某个单词出现的次数'''
try:
with open(filename,encoding='gb18030',errors='ignore') as f_obj:
contents=f_obj.read()
except FileNotFoundError:
pass
else:
num1=contents.count(word)
print(num1)
num2=contents.lower().count(word)
print(num2)
filename='Alice’s_Adventures_in_Wonderland.txt'
word='the'
count_words(filename,word)