python123机器学习基础练习1
目录
一、#172256 计算方差
二、#172266 数据集处理
三、#172290 投票
四、#209316 简易英汉字典
五、#209317 大学排行榜
六、#209318 词频统计
七、#209324 葡萄酒评论分析报告
八、#209325 素数问题
一、#172256 计算方差
def var1(n):import statisticsreturn statistics.pvariance(range(1, n + 1))if __name__ == '__main__':n = int(input())print('{:.2f}'.format(var1(n)))
注意:pvariance函数用于计算总体的方差,计算时除以的是n;variance函数用于计算样本的方差,计算时除以的是n-1;
二、#172266 数据集处理
import numpy as npdef split_train_test(data):# 取二维数组的最后一列,labels是一维向量labels = data[:, -1]# 构造布尔数组,划分训练/测试集train_mask = labels != -1test_mask = labels == -1n_train = int(np.sum(train_mask))#训练样本的数量n_test = int(np.sum(test_mask)) #测试样本的数量# 训练数据中的有效标签train_labels = labels[train_mask]n_label = len(np.unique(train_labels))return n_train, n_test, n_labelif __name__ == '__main__':data = np.loadtxt('classification_1.txt')n_train, n_test, n_label = split_train_test(data)print('训练数据数量:{}'.format(n_train))print('测试数据数量:{}'.format(n_test))print('有效标签种类数量:{}'.format(n_label))train_labels = labels[train_mask]
三、#172290 投票
def vote(elements):if not elements:raise ValueError("输入不能为空")freq = {} # 频次字典winner = None # 当前冠军max_cnt = 0 # 最高票数for e in elements:freq[e] = freq.get(e, 0) + 1if freq[e] > max_cnt: # 反超才刷新max_cnt = freq[e]winner = ereturn winnerdef main():raw = input().strip() # 按题目要求,只读一行if not raw:returnelements = raw.split() # 按空格分割print(vote(elements)) # 直接输出结果if __name__ == "__main__":main()
四、#209316 简易英汉字典
详细思路:【Python习题】简易英汉字典(project-ssss)(题目的坑解析+实现代码)_python简易英汉字典-CSDN博客
import stringdef create_dict(filename):"""接收表示文件名的字符串参数,读文件中的单词及释义,以单词为键,其他部分为值创建字典。多个释义间可能是逗号或空格分隔,但单词与第一个释义间至少有一个空格,将文件每一行根据空格切分一次,切分结果分别作为键和值创新字典。返回字典。"""word_dic = {}ls = []with open(filename, "r", encoding='UTF-8') as f:# encoding='UTF-8'防止编码问题错误for line in f.readlines():# readlines表示读取所有行line = line.strip('\n').replace("]", " ") # 去掉列表中每一个元素的换行符。此外还要replace因为真的是天坑,给我们的文件中 thursday ]n.星期四 这个单词有个“]”干扰line = line.split(" ") # 分割成列表# print(line)word_dic[line[0]] = line[1]#把这一行内容加入字典return word_dicdef translate(dic, word):"""接收两个参数,第一个是读文件创建的字典,第二个参数为要查询的单词,字符串根据文件创建的字典,从中查询单词word,如果查询单词存在,元组形式返回词与词的释义;如果查询不存在,返回'这个词我不明白'"""word=word.lower() #小写if dic.get(word, '这个词我不明白') != '这个词我不明白':return word, dic.get(word, '这个词我不明白')else:return word,'这个词我不明白'def sentence_to_words():"""调用此函数时,先输出提示信息'请输入查询的句子:'用户输入欲翻译的句子若输入非空时,先将"n't"替换为 ' not'、"'s"替换为 ' is',再将标点符号替换为空格。根据空格将句子切分为单词的列表,调用translate逐个单词进行翻译。用户可重复多次输入,每输入一名翻译一句,若直接输入回车时,输出'查询结束,正在退出...'。然后结束程序。"""s = input("请输入查询的句子:")while (s != ""):s=s.replace(".", " ").replace(", ", " ").replace("'s", " is").replace("n't"," not").split(" ")#分割和替换for i in s:#如果说分割出了空的字符串,不进行判断直接跳过if i=="":continuegetWord=translate(word_dic, i)print(getWord[0],getWord[1])s = input("请输入查询的句子:")print('查询结束,正在退出...')def translate_word():"""调用此函数时,先输出提示信息:'请输入查询的单词:'用户可循环输入欲翻译的单词,若直接输入回车时,输出'查询结束,正在退出...'。输入非空时输出翻译结果"""s = input("请输入查询的单词:")while (s != ""):print(translate(word_dic, s)[0],translate(word_dic, s)[1])s = input("请输入查询的单词:")print('查询结束,正在退出...')if __name__ == '__main__':file = './dict.txt' # 表示文件名的字符串,表示位于当前路径下的'dict.txt'文件word_dic = create_dict(file) # 调用函数返回字典类型的数据print('载入字典数据成功!查询单词请输入“1”,查询句子请输入“2”')choice = input() # 输入操作选项if choice == '1':translate_word() # 翻译单词elif choice == '2':sentence_to_words() # 翻译句子else:print('输入错误,请重新运行程序!')
五、#209317 大学排行榜
详细思路:大学排行榜分析【Python习题】(保姆级图文+实现代码)_python大学排行榜分析-CSDN博客
def read_file(file,m):"""读文件中的学校名到列表中,返回前m个记录的学校集合"""f = open(file, 'r',encoding='utf-8')lines=[]for i in range(m):line=f.readline().strip("\n")lines.append(line.split()[1])#把学校添加列表return linesdef either_in_top(alumni, soft):"""接收两个排行榜前m高校名字集合,获得在这两个排行榜中均在前m个记录的学校名,按照学校名称排序,返回排序后的列表"""result=[]for i in range(len(alumni)):if alumni[i] in soft:#如果同时在两个表中都有这个学校result.append(alumni[i])result.sort()#升序排序return resultdef all_in_top(alumni, soft):"""接收两个排行榜前m高校名字集合,获得在两个榜单中名列前m的所有学校名,按照学校名称排序,返回排序后的列表"""result=[]result.extend(alumni)#列表合并alumniresult.extend(soft)#列表合并softresult=list(set(result))#列表去重result.sort()#升序排序return resultdef only_alumni(alumni, soft):"""接收两个排行榜前m高校名字集合,获得在alumni榜单中名列前m但soft榜单中未进前m的学校名,按照学校名称排序,返回排序后的列表"""result=[]for i in range(len(alumni)):if alumni[i] in soft:continueelse:#如果在alumni榜单中名列前m但soft榜单中未进前m的学校名result.append(alumni[i])result.sort()#升序排序return resultdef only_once(alumni, soft):"""接收两个排行榜前m高校名字集合,获得在alumni和soft榜单中名列前m,但不同时出现在两个榜单的学校名,按照学校名称排序,返回排序后的列表"""result=[]for i in range(len(alumni)):if alumni[i] in soft:continueelse:#如果在alumni榜单中名列前m但soft榜单中未进前m的学校名result.append(alumni[i])for i in range(len(soft)):if soft[i] in alumni:continueelse:#如果在soft榜单中名列前m但alumni榜单中未进前m的学校名result.append(soft[i])result.sort()#升序排序return resultdef judge(n):if n in '1234':m=int(input())alumni_set = read_file('./alumni.txt',m)soft_set = read_file('./soft.txt',m)if n=='1':either_rank = either_in_top(alumni_set, soft_set)print(f'两榜单中均名列前{m}的学校:')print(either_rank)elif n=='2':all_rank = all_in_top(alumni_set, soft_set)print(f'两榜单名列前{m}的所有学校:')print(all_rank)elif n=='3':only_in_alumni_rank = only_alumni(alumni_set, soft_set)print(f'alumni中名列前{m},soft中未进前{m}的学校:')print(only_in_alumni_rank)elif n=='4':alumni_soft_rank = only_once(alumni_set, soft_set)print(f'不同时出现在两个榜单前{m}的学校:')print(alumni_soft_rank)else:print('Wrong Option')if __name__ == '__main__':num = input()judge(num)
六、#209318 词频统计
详细思路:
Python词频统计:《谁动了我的奶酪》故事分析-CSDN博客
修改后的代码为:
import stringdef read_file(file):"""接收文件名为参数,将文件中的内容读为字符串,只保留文件中的英文字母和西文符号,过滤掉中文(中文字符及全角符号Unicode编码都大于256)将所有字符转为小写,将其中所有标点、符号替换为空格,返回字符串"""with open(file, 'r', encoding='utf-8') as data:text = data.read()text_new = ''for i in text:if(ord(i) < 256):text_new = text_new+itext_new = text_new.lower() # 将所有的英文大写字母转化为小写字母# S = set()# for i in text_new:# if not (i >= 'a' and i <= 'z'):# S.add(i)# print(S)# {'"', ';', '\n', '8', '?', ':', '9', '6', ',', '3', '~', '2', '4', '!', '-', '5', '1', '0', ' ', "'", '.', '7'}# text_new = text_new.replace('\n', '') # 去除换行符list_deldete = ['.', ',', '\"', '\'', ':', '!', '-', '?', '~', ';']for i in list_deldete:text_new = text_new.replace(i, ' ')# 根据测试案例一可知,换行符没有被删除,多余的空格也没有被删除,数字也没有被删除'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'# print(text_new)return text_newdef count_of_words(txt):"""接收去除标点、符号的字符串,统计并返回其中单词数量和不重复的单词数量"""word_list = txt.split()total = len(word_list) # 总单词数unique = len(set(word_list)) # 不重复单词数return total, uniquedef word_frequency(txt):"""接收去除标点、符号的字符串,统计并返回每个单词出现的次数返回值为字典类型,单词为键,对应出现的次数为值"""word_list = txt.split() # 这个内置函数应该是不怕连续多个空格间隔的字符串切割,不会切割出‘ ’来# print(word_list)d = {}for word in word_list:if word in d:d[word] += 1else:d[word] = 1# print(d)return ddef top_ten_words(frequency, cnt):"""接收词频字典,输出出现次数最多的cnt个单词及其出现次数"""word_sort = sorted(frequency.items(),key=lambda x: x[1], reverse=True) # 根据词频降序排序# word_sort的类型是list,其中每一个元素是元组# print(word_sort)for i in range(cnt):print(word_sort[i][0], word_sort[i][1])def top_ten_words_no_excludes(frequency, cnt):"""接收词频字典,去除常见的冠词、代词、系动词和连接词后,输出出现次数最多的cnt个单词及其出现次数,需排除的单词如下:excludes_words = ['a', 'an', 'the', 'i', 'he', 'she', 'his', 'my', 'we','or', 'is', 'was', 'do', 'and', 'at', 'to', 'of', 'it', 'on', 'that', 'her','c','in', 'you', 'had','s', 'with', 'for', 't', 'but', 'as', 'not', 'they', 'be', 'were', 'so', 'our','all', 'would', 'if', 'him', 'from', 'no', 'me', 'could', 'when', 'there','them', 'about', 'this', 'their', 'up', 'been', 'by', 'out', 'did', 'have']"""excludes_words = ['a', 'an', 'the', 'i', 'he', 'she', 'his', 'my', 'we','or', 'is', 'was', 'do', 'and', 'at', 'to', 'of', 'it', 'on', 'that', 'her','c', 'in', 'you', 'had', 's', 'with', 'for', 't', 'but', 'as', 'not', 'they','be', 'were', 'so', 'our', 'all', 'would', 'if', 'him', 'from', 'no', 'me','could', 'when', 'there', 'them', 'about', 'this', 'their', 'up', 'been','by', 'out', 'did', 'have']word_sort = sorted(frequency.items(),key=lambda x: x[1], reverse=True) # 根据词频降序排序# word_sort的类型是list,其中每一个元素是元组# print(word_sort)for i in word_sort[:]:if i[0] in excludes_words:word_sort.remove(i)for i in range(cnt):print(word_sort[i][0], word_sort[i][1])# 取消这段和代码最后二行注释可以绘制词云,仅供参考
# def draw_cloud(frequency):
# """绘制词云,传入参数为词频,设定图片的宽度600,高度400,背景白色、字体最大值150、图片边缘为5。"""
# wc = WordCloud(max_words=80, # 设置显示高频单词数量
# width=600, # 设置图片的宽度
# height=400, # 设置图片的高度
# background_color='White', # 设置背景颜色
# max_font_size=150, # 设置字体最大值
# margin=5, # 设置图片的边缘
# scale=1.5) # 按照比例进行放大画布,如设置为1.5,则长和宽都是原来画布的1.5倍。
# wc.generate_from_frequencies(frequency) # 根据文本内容直接生成词云
# plt.imshow(wc) # 负责对图像进行处理,并显示其格式,但是不能显示。
# plt.axis("off") # 不显示坐标轴
# wc.to_file('My Cheese.png') # 词云保存为图片
# plt.show() # 显示图像if __name__ == '__main__':filename = 'Who Moved My Cheese.txt' # 文件名content = read_file(filename) # 调用函数返回字典类型的数据frequency_result = word_frequency(content) # 统计词频cmd = input()if cmd == '1':n = int(input())print(content[:n])elif cmd == '2':amount_results = count_of_words(content)print('文章共有单词{}个,其中不重复单词{}个'.format(*amount_results))elif cmd == '3':n = int(input())top_ten_words(frequency_result, n)elif cmd == '4':n = int(input())top_ten_words_no_excludes(frequency_result, n)# frequency_no_excludes = top_ten_words_no_excludes(frequency_result)# draw_cloud(frequency_no_excludes)
七、#209324 葡萄酒评论分析报告
详细思路:
(头歌作业)—6.1 葡萄酒评论分析报告(project)_6.1 葡萄酒评论分析报告(project)实验总用时:00:00:03 资源中心 数据集 nav -CSDN博客
修改后:
# 1 统计文件中出现的葡萄酒生产国家,输出不重复的国家名列表,按字母
# 表升序排序, 若国家名数据缺失,略过该条数据,返回值中不包含空字符串元素
# 2 计算每个国家的葡萄酒的平均得分,返回值为国家名和得分的列表
# 3 计算每个国家的葡萄酒的平均得分,返回值为国家名和得分的列表,按评分由高到低降序排列
# 4 评分最高的十款葡萄酒的编号、出产国、评分和价格,按评分降序输出
# 5 价格最高的二十款葡萄酒的编号、出产国、评分和价格,按价格降序输出
# 6 统计各个评分的葡萄酒数量是多少?输出包含评分和数量的列表
# 7 输出拥有葡萄酒数量最多的评分和数量
# 8 输出拥有葡萄酒数量最多的评分的葡萄酒的平均价格import pandas as pd
import math# 定义符号常量,用于索引,使之具有清晰的语义
NUMBER = 0
COUNTRY = 1
DESCRIPTION = 2
POINTS = 3
PRICE = 4
PROVINCE = 5def csv_to_ls(file):"""接收文件名为参数,用pandas读取数据为dataframe格式,再将其数据部分(values)用tolist()方法转为二维列表,返回这个二维列表。@参数 file:文件名,字符串类型"""wine_list = pd.read_csv(file).values.tolist()return wine_listdef country_ls(wine_list):"""接收列表格式的葡萄酒数据为参数,略过标题行,返回不重复的国家名列表,按字母表升序排序,若国家名数据缺失,略过该条数据,返回值中不包含空字符串元素。@参数 wine_list:葡萄酒数据,列表类型"""country_list = []for x in wine_list:if x[COUNTRY] not in country_list and x[COUNTRY]:country_list.append(x[COUNTRY])country_list.sort()return country_listdef avg_point(wine_list, country):"""接收列表格式的葡萄酒数据和国家名列表为参数,计算每个国家的葡萄酒的平均得分,返回值为国家名和得分的列表。@参数 wine_list:葡萄酒数据,列表类型@参数 country:国家名,列表类型"""result = []for c in country:points = []for line in wine_list[1:]:if line[COUNTRY] == c:points.append(float(line[POINTS]))if points:avg = round(sum(points) / len(points), 2)result.append([c, avg])return resultdef avg_point_sort(wine_list, country):"""接收列表格式的葡萄酒数据和国家名列表为参数,计算每个国家的葡萄酒的平均得分,返回值为国家名和得分的列表,按评分由高到低降序排列。@参数 wine_list:葡萄酒数据,列表类型@参数 country:国家名,列表类型"""country_avg_points = []for c in country:points = []for wine in wine_list:if wine[COUNTRY] == c and not math.isnan(wine[POINTS]):points.append(wine[POINTS])if points:avg_point = round(sum(points) / len(points), 2)country_avg_points.append([c, avg_point])country_avg_points.sort(key=lambda x: x[1], reverse=True)return country_avg_pointsdef top_10_point(wine_list):"""接收列表格式的葡萄酒数据参数,返回评分最高的十款葡萄酒的编号、出产国、评分和价格,按评分降序输出。需要注意的是评分可能有缺失值,此时该数据为nanif math.isnan(x) == False可用于判定x的值是不是nannan的数据类型是float,不可以直接用字符串判定方法。@参数 wine_list:葡萄酒数据,列表类型"""filtered_wine_list = [wine for wine in wine_list if not math.isnan(wine[POINTS])]top_10_wines = sorted(filtered_wine_list, key=lambda x: x[POINTS], reverse=True)[:10]result = [[wine[NUMBER], wine[COUNTRY], wine[POINTS], wine[PRICE]] for wine in top_10_wines]return resultdef top_20_price(wine_list):"""接收列表格式的葡萄酒数据参数,返回价格最高的二十款葡萄酒的编号、出产国、评分和价格,按价格降序输出。@参数 wine_list:葡萄酒数据,列表类型需要注意的是价格可能有缺失值,此时该数据为nanif math.isnan(x) == False可用于判定x的值是不是nannan的数据类型是float,不可以直接用字符串判定方法。"""valid_wine_list = [wine for wine in wine_list if not math.isnan(wine[PRICE])]sorted_wine_list = sorted(valid_wine_list, key=lambda x: x[PRICE], reverse=True)top_20 = sorted_wine_list[:20]result = [[wine[NUMBER], wine[COUNTRY], wine[POINTS], wine[PRICE]] for wine in top_20]return resultdef amount_of_point(wine_list):"""接收列表格式的葡萄酒数据参数,统计每个评分的葡萄酒数量,忽略没有评分的数据。返回二维列表,按评分升序排序。例如[...[84, 645], [85, 959],...]表示得分为84的葡萄酒645种,得分85的葡萄酒有959种。@参数 wine_list:葡萄酒数据,列表类型"""point_count = {}for wine in wine_list:if not math.isnan(wine[POINTS]):point = int(wine[POINTS])point_count[point] = point_count.get(point, 0) + 1result = [[k, v] for k, v in sorted(point_count.items())]return resultdef most_of_point(amount_of_points):"""接收每个评分的葡萄酒数量的列表为参数,返回获得该分数数量最多的评分和数量的列表。@参数 amount_of_points:每个评分的葡萄酒数量,列表类型"""max_count = 0max_point = Nonefor point, count in amount_of_points:if count > max_count:max_count = countmax_point = pointreturn [max_point, max_count]def avg_price_of_most_point(wine_list, most_of_points):"""接收列表格式的葡萄酒数据和获得最多的评分及数量的列表为参数忽略缺失价格的数据,返回这个分数的葡萄酒的平均价格,保留2位小数。@参数 wine_list:葡萄酒数据,列表类型@参数 most_of_points:获得最多的评分及数量,列表类型"""total_price = 0count = 0most_point = most_of_points[0]for wine in wine_list:if not math.isnan(wine[POINTS]) and not math.isnan(wine[PRICE]) and wine[POINTS] == most_point:total_price += wine[PRICE]count += 0 if math.isnan(wine[PRICE]) else 1return round(total_price / count, 2)def judge(txt):"""接收一个字符串为参数,根据参数值调用不同函数完成任务"""filename = './winemag-data.csv'wine = csv_to_ls(filename)country = country_ls(wine)if txt == '国家名列表':print(country)elif txt == '平均分':print(avg_point(wine, country)) # 每个国家的葡萄酒的平均得分elif txt == '平均分排序':print(avg_point_sort(wine, country)) # 每个国家的葡萄酒的平均得分降序输出elif txt == '评分最高':print(top_10_point(wine)) # 评分最高的十款葡萄酒的编号、出产国、评分和价格,按评分降序输出elif txt == '价格最高':print(top_20_price(wine)) # 价格最高的二十款葡萄酒的编号、出产国、评分和价格,按价格降序输出elif txt == '葡萄酒评分':amount_point = amount_of_point(wine)most_point = most_of_point(amount_point)print(amount_point) # 各个评分的葡萄酒数量print(most_point) # 拥有葡萄酒数量最多的评分和数量print(avg_price_of_most_point(wine, most_point)) # 拥有葡萄酒数量最多的评分的葡萄酒的平均价格else:print('输入错误')if __name__ == '__main__':text = input()judge(text)
八、#209325 素数问题
详细思路:
Python学习37:素数问题(python123)_为了完成本关任务,你需要掌握: 寻找回文素数 寻找回文素数 如果一个整数是素数,同-CSDN博客
def question_judge(question):"""接收一个字符串为参数,根据参数值判断问题类型,调用合适的函数进行操作。"""if question == '素数': # 如果输入”素数“,再输入一个正整数n,输出不大于n的所有素数n = int(input())output_prime(n) # 输出素数elif question == '回文素数':n = int(input())palindromic_prime(n) # 输出回文素数elif question == '反素数':n = int(input())reverse_prime(n) # 输出反素数elif question == '哥德巴赫猜想':n = int(input())goldbach_conjecture(n)else:print('输入错误')def is_prime(n):"""判断素数的函数,接收一个正整数为参数,参数是素数时返回True,否则返回False减小判定区间,减少循环次数,提升效率"""if n < 2:return Falsefor i in range(2,int(n**0.5+1)): if n % i == 0:return Falseelse:return Truedef output_prime(number):"""接收一个正整数为参数,遍历从0到number之间的所有整数在一行中输出不大于number的所有素数,函数无返回值"""for i in range(number+1):if is_prime(i)==True:print(i,end=' ')def palindromic(num):"""接收一个数字为参数,判定其是否为回文数,返回布尔值。"""return str(num) == str(num)[::-1]def palindromic_prime(number):"""接收一个正整数参数number,遍历从0到number之间的所有整数,若某个数是素数,且转为字符串后是回文字符串,则称其为回文素数找出并在同一行中从小到大输出小于number的所有回文素数,各数字间用一个空格分隔,函数无返回值"""for i in range(number+1):if palindromic(i)==True and is_prime(i)==True:print(i,end=' ')def reverse_num(num):"""接收一个整数,返回其逆序字符串对应的整数"""return int(str(num)[::-1])def reverse_prime(number):"""接收一个正整数参数,找出并在同一行内输出所有小于number的反素数,数字间用一个空格分隔。反素数指某数i及其逆序数都是素数,但数i对应的字符串不是回文字符串函数无返回值"""for i in range(number):if palindromic(i)==False and is_prime(i)==True and is_prime(reverse_num(i))==True :print(i,end=' ')def goldbach_conjecture(num):""" 哥德巴赫猜想, 接收一个不小于4的正整数为参数。当参数为不小于4的偶数时,将其分解为两个素数的加和,按小数+数的格式输出。有多种组合时全部输出,但不输出重复的组合,例如输出8=3+5,不输出8=5+3。参数为奇数或小于4时,输出'Data error!'"""if num %2==0 and num>=4:for i in range(2,(num//2)+1):if is_prime(i)==True and is_prime(num-i)==True:print(f"{num}={i}+{num-i}")else:print("Data error!")if __name__ == '__main__':problems = input()question_judge(problems)