1. 复习week 5 lecture 5.3 B, 5.3 C
2. 练习题(前6题)
3. 拓展升级练习 + 夯实基础
FileIO 复习
students = tuple() #标准形式
with open('s.txt') as f:
for line in f:
students += int(line),#不断创建tuple
print(len(students))
检测 remove() 语法括号里的内容是value还是index
#删除括号里的值
li = [1, 2, 3, 4, 5]
li.remove(2)
print(li)
可变参数
#可变参数, 调用时候比声明时传入了更多的参数
def show(file_path, *args, **kwargs):
print(file_path)
print("*args = ", args)
print("*kwargs = ", kwargs)
show('22222', 'aaa','bbb',haha = 'xxx')
sorted用法
ls = [
{'name': 'eric', 'grade':100, 'age':65},
{'name': 'haha', 'grade':33, 'age':44},
{'name': 'eee', 'grade':33, 'age':44},
{'name': 'eer', 'grade':11, 'age':22},
]
info = {'eric':100, 'eee':22, '22':33, 'ss':44, }
print(info)
ls_info = list(info.items())#变成列表元组形式
print(ls_info)
# def guizi(d):
# return d['grade'] #通过key来排序
# print(sorted(ls, key=guizi))
print(sorted(ls, key=lambda x:x['age']))
print(sorted(ls_info, key=lambda x:x[1], reverse=True))
类型与类型之间的互转
#字典与列表互转
info = {'eric':100, 'eee':22, '22':33, 'ss':44, }
for key in info:
print(info[key])
for k, v in info.items():
print(k, v)
print(list(info.values()))
print(list(info.keys()))
print(list(info.items()))
ls = [('eric', 100), ('eee', 22), ('22', 33), ('ss', 44)]
print(dict(ls))
#列表跟字符串之间的转化
print(list('abccde'))
li = ['a', 'b', 'c', 'c', 'd', 'e']
print(''.join(li))
print(' '.join(li))
print('/'.join(li))
#元组跟列表
li = ['a', 'b', 'c', 'c', 'd', 'e']
print(tuple(li))
t = ('a', 'b', 'c', 'c', 'd', 'e')
print(list(t))
#集合和列表
li = ['a', 'b', 'c', 'c', 'a', 'a']
print(set(li))
print(list(set(li)))
歌词查重次数
example:《BLUE》Troye Sivan
创建 blue.txt,粘贴歌词
test3 运行程序
简单查重程序如下:
with open('blue.txt') as f:
data = f.read()
data = data.replace(',','')
data1 = data.split(' ')
print(data1)
counts = {}
for word in data1:
counts[word] = counts.get(word, 0) +1
print(counts)
li = list(counts.items())
print(li)
li.sort(key=lambda x:x[1], reverse = True)
print(li[:2])
stopwords规避之后,歌词查重
引用stopwords.txt
with open('blue.txt') as f:
data = f.read()
data = data.replace(',','')
data1 = data.split(' ')
print(data1)
counts = {}
for word in data1:
counts[word] = counts.get(word, 0) +1
print(counts)
#stopwords规避常用词
stopwords = set(open('stopwords.txt').read().split())
for word in stopwords:
if word in counts.keys():
del counts[word]
#遍历并删除歌词中的常用词
li = list(counts.items())
print(li)
li.sort(key=lambda x:x[1], reverse = True)
print(li[:2])