文件操作:
#方法split以空格为分隔符将字符串分拆成多个部分
title = “Alice in Wonderland”
print(title.split())
[‘Alice’, ‘in’, ‘Wonderland’]
对文件进行异常情况操作及单词计数
def count_words(filename):
“”“计算一个文件大致包含多少个单词”“”
try:#表示条件
with open(filename,encoding=‘utf-8’) as f:
contents = f.read()
except FileNotFoundError:#表示出现异常时
print(f"Sorry,the file {filename} dose not exist.“)
else:#表示正常情况下对文件操作
words = contents.split()
num_words = len(words)
print(f"The file {filename} has about {num_words} words.”)
filename = ‘alice.txt’
count_words(filename)
pass语句的作用
def count_words(filename):
“”“计算一个文件大致包含多少个单词”“”
try:
with open(filename,encoding=‘utf-8’) as f:
contents = f.read()
except FileNotFoundError:
pass#告诉程序什么都不用做,
# print(f"Sorry,the file {filename} dose not exist.“)
else:
words = contents.split()
num_words = len(words)
print(f"The file {filename} has about {num_words} words.”)
filename = ‘alice.txt’
count_words(filename)
存储数据- json模块
将简单的数据结构转存到python中
import json
filename = ‘numbers.json’
with open(filename) as f:
#使用函数json.load()加载存储在numbers.json中的信息
numbers = json.load(f)
print(numbers)
import json
numbers = [2,3,5,7,11,13]
#将.ison来指出文件存储的数据格式
filename = ‘numbers.json’
with open(filename,‘w’) as f:
#使用函数json.dump将数字列表存储到文件中
json.dump(numbers,f)
重构-通过划分成统一可规划的函数,
单元测试和用例测试
#导入模块和要测试的函数
import unittest
from name_function import get_formatted_name
#创建名为NamesTestCase的类,用于包含一系列针对get_formatted_named的单元测试
#类可以随意命名,但最好看起来与要测试的函数相关并包含Test字样
#类必须继承unittest.TestCase类,这样python才知道如何运行编写的测试
class NamesTestCase(unittest.TestCase):
“”“测试name_function.py”“”
def test_first_last_name(self):
“”“能正确处理像Janis Joplin这样的姓名吗?”“”
formatted_name = get_formatted_name(‘janis’,‘joplin’)
#断言方法,断言方法核实得到的结果和期望的结果一致
self.assertEqual(formatted_name,‘Janis Joplin’)
def test_first_last_middle_name(self):
“”“能够正确地处理像Wolfgang Amadeus Mozart这样的姓名吗?”“”
formatted_name = get_formatted_name(‘wolfgang’,‘mozart’,‘amadeus’)
self.assertEqual(formatted_name,‘Wolfgang Amadeus Mozart’)
if name == ‘main’:
unittest.main()
测试类
【无标题】
最新推荐文章于 2024-06-13 23:55:30 发布